def crop_and_pad_voxels(voxels, start_coordinates, end_coordinates):
  """Crops a voxel region and pads past the boundaries with zeros.

  This accepts start and end coordinates past the limits of the voxel grid,
  and uses it to calculate how much top/left/right/bottom padding to add.

  Args:
    voxels: A tf.float32 tensor of shape [x, y, z, f] to crop
    start_coordinates: A list of len 4 with the [x, y, z, f] starting location
      of our crop. This can be negative, which indicates left/top padding.
    end_coordinates: A list of len 4 with the [x, y, z, f] ending location of
      our crop. This can be beyond the size of the voxel tensor, which indicates
      padding.

  Returns:
    cropped_and_padded_voxels: A voxel grid with shape
      [end_coordinates[0] - start_coordinates[0],
       end_coordinates[1] - start_coordinates[1],
       end_coordinates[2] - start_coordinates[2],
       end_coordinates[3] - start_coordinates[3]]
  Raises:
    ValueError: If requested crop and pad is outside the bounds of what the
      function supports.
  """
  if len(start_coordinates) != 4:
    raise ValueError('start_coordinates should be of length 4')
  if len(end_coordinates) != 4:
    raise ValueError('end_coordinates should be of length 4')
  if any([coord <= 0 for coord in end_coordinates]):
    raise ValueError('Requested end coordinates should be > 0')

  start_coordinates = tf.convert_to_tensor(start_coordinates, tf.int32)
  end_coordinates = tf.convert_to_tensor(end_coordinates, tf.int32)

  # Clip the coordinates to within the voxel grid
  clipped_start_coordinates = tf.maximum(0, start_coordinates)
  clipped_end_coordinates = tf.minimum(voxels.shape, end_coordinates)

  cropped_voxels = tf.slice(voxels,
                            begin=clipped_start_coordinates,
                            size=(clipped_end_coordinates -
                                  clipped_start_coordinates))

  top_and_left_padding = tf.maximum(0, -start_coordinates)
  bottom_and_right_padding = tf.maximum(0, end_coordinates - voxels.shape)

  padding = tf.stack([top_and_left_padding, bottom_and_right_padding], axis=1)
  return tf.pad(cropped_voxels, padding)