Convert an OpenHTF test record attachment to a multi-dim measurement.

  This is a best effort attempt to reverse, as some data is lost in converting
  from a multidim to an attachment.

  Args:
    attachment: an `openhtf.test_record.Attachment` from a multi-dim.
    name: an optional name for the measurement.  If not provided will use the
     name included in the attachment.

  Returns:
    An multi-dim `openhtf.Measurement`.

def attachment_to_multidim_measurement(attachment, name=None):
  """Convert an OpenHTF test record attachment to a multi-dim measurement.

  This is a best effort attempt to reverse, as some data is lost in converting
  from a multidim to an attachment.

  Args:
    attachment: an `openhtf.test_record.Attachment` from a multi-dim.
    name: an optional name for the measurement.  If not provided will use the
     name included in the attachment.

  Returns:
    An multi-dim `openhtf.Measurement`.
  """
  data = json.loads(attachment.data)

  name = name or data.get('name')
  # attachment_dimn are a list of dicts with keys 'uom_suffix' and 'uom_code'
  attachment_dims = data.get('dimensions', [])
  # attachment_value is a list of lists [[t1, x1, y1, f1], [t2, x2, y2, f2]]
  attachment_values = data.get('value')

  attachment_outcome_str = data.get('outcome')
  if attachment_outcome_str not in TEST_RUN_STATUS_NAME_TO_MEASUREMENT_OUTCOME:
    # Fpr backward compatibility with saved data we'll convert integers to str
    try:
      attachment_outcome_str = test_runs_pb2.Status.Name(
          int(attachment_outcome_str))
    except ValueError:
      attachment_outcome_str = None

  # Convert test status outcome str to measurement outcome
  outcome = TEST_RUN_STATUS_NAME_TO_MEASUREMENT_OUTCOME.get(
      attachment_outcome_str)

  # convert dimensions into htf.Dimensions
  _lazy_load_units_by_code()
  dims = []
  for d in attachment_dims:
    # Try to convert into htf.Dimension including backwards compatibility.
    unit = UNITS_BY_CODE.get(d.get('uom_code'), units.NONE)
    description = d.get('name', '')
    dims.append(measurements.Dimension(description=description, unit=unit))

  # Attempt to determine if units are included.
  if attachment_values and len(dims) == len(attachment_values[0]):
    # units provided
    units_ = dims[-1].unit
    dimensions = dims[:-1]
  else:
    units_ = None
    dimensions = dims

  # created dimensioned_measured_value and populate with values.
  measured_value = measurements.DimensionedMeasuredValue(
      name=name,
      num_dimensions=len(dimensions)
  )
  for row in attachment_values:
    coordinates = tuple(row[:-1])
    val = row[-1]
    measured_value[coordinates] = val

  measurement = measurements.Measurement(
      name=name,
      units=units_,
      dimensions=tuple(dimensions),
      measured_value=measured_value,
      outcome=outcome
  )
  return measurement