import torch


def bbox2loc(bbox_a, bbox):
	""" compute offsets and scales given target and source bounding boxes.

	Args:
		bbox: (R, 4) contains (x1, y1, x2, y2)
		bbox_a: (R, 4) contains (x1, y1, x2, y2)

	Returns:
		(R, 4) contains (tx, ty, tw, th)
	"""
	assert bbox.size(1) == bbox_a.size(1) == 4 and bbox.size(0) == bbox_a.size(0)

	w_a = bbox_a[:, 2] - bbox_a[:, 0]
	h_a = bbox_a[:, 3] - bbox_a[:, 1]
	ctr_x_a = bbox_a[:, 0] + 0.5 * w_a
	ctr_y_a = bbox_a[:, 1] + 0.5 * h_a

	w = bbox[:, 2] - bbox[:, 0]
	h = bbox[:, 3] - bbox[:, 1]
	ctr_x = bbox[:, 0] + 0.5 * w
	ctr_y = bbox[:, 1] + 0.5 * h

	tx = (ctr_x - ctr_x_a) / w_a
	ty = (ctr_y - ctr_y_a) / h_a
	th = torch.log(h / h_a)
	tw = torch.log(w / w_a)

	return torch.stack([tx, ty, tw, th]).transpose(0, 1)