import math


def _decode_box_encoding(box_encoding, anchor, image_size):
  """Decodes bounding box encoding.

  Args:
    box_encoding: a tuple of 4 floats.
    anchor: a tuple of 4 floats.
    image_size: a tuple of 2 ints, (width, height)
  Returns:
    A tuple of 4 integer, in the order of (left, upper, right, lower).
  """
  assert len(box_encoding) == 4
  assert len(anchor) == 4
  y_scale = 10.0
  x_scale = 10.0
  height_scale = 5.0
  width_scale = 5.0

  rel_y_translation = box_encoding[0] / y_scale
  rel_x_translation = box_encoding[1] / x_scale
  rel_height_dilation = box_encoding[2] / height_scale
  rel_width_dilation = box_encoding[3] / width_scale

  anchor_ymin, anchor_xmin, anchor_ymax, anchor_xmax = anchor
  anchor_ycenter = (anchor_ymax + anchor_ymin) / 2
  anchor_xcenter = (anchor_xmax + anchor_xmin) / 2
  anchor_height = anchor_ymax - anchor_ymin
  anchor_width = anchor_xmax - anchor_xmin

  ycenter = anchor_ycenter + anchor_height * rel_y_translation
  xcenter = anchor_xcenter + anchor_width * rel_x_translation
  height = math.exp(rel_height_dilation) * anchor_height
  width = math.exp(rel_width_dilation) * anchor_width

  image_width, image_height = image_size
  x0 = int(max(0.0, xcenter - width / 2) * image_width)
  y0 = int(max(0.0, ycenter - height / 2) * image_height)
  x1 = int(min(1.0, xcenter + width / 2) * image_width)
  y1 = int(min(1.0, ycenter + height / 2) * image_height)
  return (x0, y0, x1 - x0, y1 - y0)