Create a 1d mesh tensor with a range from [0, dim.size).

  Call externally as mtf.range()

  Args:
    mesh: a Mesh
    dim: a Dimension
    dtype: a tf.DType
    name: an optional string

  Returns:
    a Tensor
332454
def mtf_range(mesh, dim, dtype, name=None):
  
  dim = convert_to_dimension(dim)
  with tf.variable_scope(name, default_name="range"):
    if dtype == tf.bfloat16:
      # tf.range(dtype=bfloat16) gives the wrong shape.
      # TODO(noam): report the bug.
      tf_range = tf.cast(tf.range(dim.size), tf.bfloat16)
    else:
      tf_range = tf.range(dim.size, dtype=dtype)
    return import_tf_tensor(mesh, tf_range, shape=Shape([dim]))
1236581
def mesh(self,xyzs):
        
        return sum(c*p.mesh(xyzs) for c,p in self)
1079337
def create(input_shape):
    
    if isinstance(input_shape, numbers.Number):
        input_shape = (input_shape,)
    elif not isinstance(input_shape, tuple):
        input_shape = tuple(input_shape)

    def instantiate(**_):
        return NormalizeObservations(input_shape)

    return ModelFactory.generic(instantiate)
983860
def mesh_nmasked(self):
        

        return self._make_2d_array(
            np.ma.count_masked(self._data_sigclip, axis=1))
934316
def cube(
    xmin=0.0, xmax=1.0, ymin=0.0, ymax=1.0, zmin=0.0, zmax=1.0, nx=11, ny=11, nz=11
):
    
    # Generate suitable ranges for parametrization
    x_range = numpy.linspace(xmin, xmax, nx)
    y_range = numpy.linspace(ymin, ymax, ny)
    z_range = numpy.linspace(zmin, zmax, nz)

    # Create the vertices.
    x, y, z = numpy.meshgrid(x_range, y_range, z_range, indexing="ij")
    # Alternative with slightly different order:
    # ```
    # nodes = numpy.stack([x, y, z]).T.reshape(-1, 3)
    # ```
    nodes = numpy.array([x, y, z]).T.reshape(-1, 3)

    # Create the elements (cells).
    # There is 1 way to split a cube into 5 tetrahedra,
    # and 12 ways to split it into 6 tetrahedra.
    # See
    # <http://www.baumanneduard.ch/Splitting%20a%20cube%20in%20tetrahedras2.htm>
    # Also interesting: <http://en.wikipedia.org/wiki/Marching_tetrahedrons>.

    a0 = numpy.add.outer(numpy.array(range(nx - 1)), nx * numpy.array(range(ny - 1)))
    a = numpy.add.outer(a0, nx * ny * numpy.array(range(nz - 1)))

    # The general scheme here is:
    #  * Initialize everything with `a`, equivalent to
    #    [i + nx * j + nx*ny * k].
    #  * Add the "even" elements.
    #  * Switch the element styles for every other element to make sure the
    #    edges match at the faces of the cubes.
    # The last step requires adapting the original pattern at
    #     [1::2, 0::2, 0::2, :]
    #     [0::2, 1::2, 0::2, :]
    #     [0::2, 0::2, 1::2, :]
    #     [1::2, 1::2, 1::2, :]
    #

    # Tetrahedron 0:
    # [
    # i   + nx*j     + nx*ny * k,
    # i   + nx*(j+1) + nx*ny * k,
    # i+1 + nx*j     + nx*ny * k,
    # i   + nx*j     + nx*ny * (k+1)
    # ]
    # TODO get
    # ```
    # elems0 = numpy.stack([a, a + nx, a + 1, a + nx*ny]).T
    # ```
    # back.
    elems0 = numpy.concatenate(
        [a[..., None], a[..., None] + nx, a[..., None] + 1, a[..., None] + nx * ny],
        axis=3,
    )

    # Every other element cube:
    # [
    # i+1 + nx * j     + nx*ny * k,
    # i+1 + nx * (j+1) + nx*ny * k,
    # i   + nx * j     + nx*ny * k,
    # i+1 + nx * j     + nx*ny * (k+1)
    # ]
    elems0[1::2, 0::2, 0::2, 0] += 1
    elems0[0::2, 1::2, 0::2, 0] += 1
    elems0[0::2, 0::2, 1::2, 0] += 1
    elems0[1::2, 1::2, 1::2, 0] += 1

    elems0[1::2, 0::2, 0::2, 1] += 1
    elems0[0::2, 1::2, 0::2, 1] += 1
    elems0[0::2, 0::2, 1::2, 1] += 1
    elems0[1::2, 1::2, 1::2, 1] += 1

    elems0[1::2, 0::2, 0::2, 2] -= 1
    elems0[0::2, 1::2, 0::2, 2] -= 1
    elems0[0::2, 0::2, 1::2, 2] -= 1
    elems0[1::2, 1::2, 1::2, 2] -= 1

    elems0[1::2, 0::2, 0::2, 3] += 1
    elems0[0::2, 1::2, 0::2, 3] += 1
    elems0[0::2, 0::2, 1::2, 3] += 1
    elems0[1::2, 1::2, 1::2, 3] += 1

    # Tetrahedron 1:
    # [
    # i   + nx*(j+1) + nx*ny * k,
    # i+1 + nx*(j+1) + nx*ny * k,
    # i+1 + nx*j     + nx*ny * k,
    # i+1 + nx*(j+1) + nx*ny * (k+1)
    # ]
    # elems1 = numpy.stack([a + nx, a + 1 + nx, a + 1, a + 1 + nx + nx*ny]).T
    elems1 = numpy.concatenate(
        [
            a[..., None] + nx,
            a[..., None] + 1 + nx,
            a[..., None] + 1,
            a[..., None] + 1 + nx + nx * ny,
        ],
        axis=3,
    )

    # Every other element cube:
    # [
    # i+1 + nx * (j+1) + nx*ny * k,
    # i   + nx * (j+1) + nx*ny * k,
    # i   + nx * j     + nx*ny * k,
    # i   + nx * (j+1) + nx*ny * (k+1)
    # ]
    elems1[1::2, 0::2, 0::2, 0] += 1
    elems1[0::2, 1::2, 0::2, 0] += 1
    elems1[0::2, 0::2, 1::2, 0] += 1
    elems1[1::2, 1::2, 1::2, 0] += 1

    elems1[1::2, 0::2, 0::2, 1] -= 1
    elems1[0::2, 1::2, 0::2, 1] -= 1
    elems1[0::2, 0::2, 1::2, 1] -= 1
    elems1[1::2, 1::2, 1::2, 1] -= 1

    elems1[1::2, 0::2, 0::2, 2] -= 1
    elems1[0::2, 1::2, 0::2, 2] -= 1
    elems1[0::2, 0::2, 1::2, 2] -= 1
    elems1[1::2, 1::2, 1::2, 2] -= 1

    elems1[1::2, 0::2, 0::2, 3] -= 1
    elems1[0::2, 1::2, 0::2, 3] -= 1
    elems1[0::2, 0::2, 1::2, 3] -= 1
    elems1[1::2, 1::2, 1::2, 3] -= 1

    # Tetrahedron 2:
    # [
    # i   + nx*(j+1) + nx*ny * k,
    # i+1 + nx*j     + nx*ny * k,
    # i   + nx*j     + nx*ny * (k+1),
    # i+1 + nx*(j+1) + nx*ny * (k+1)
    # ]
    # elems2 = numpy.stack([a + nx, a + 1, a + nx*ny, a + 1 + nx + nx*ny]).T
    elems2 = numpy.concatenate(
        [
            a[..., None] + nx,
            a[..., None] + 1,
            a[..., None] + nx * ny,
            a[..., None] + 1 + nx + nx * ny,
        ],
        axis=3,
    )

    # Every other element cube:
    # [
    # i+1 + nx * (j+1) + nx*ny * k,
    # i   + nx * j     + nx*ny * k,
    # i+1 + nx * j     + nx*ny * (k+1),
    # i   + nx * (j+1) + nx*ny * (k+1)
    # ]
    elems2[1::2, 0::2, 0::2, 0] += 1
    elems2[0::2, 1::2, 0::2, 0] += 1
    elems2[0::2, 0::2, 1::2, 0] += 1
    elems2[1::2, 1::2, 1::2, 0] += 1

    elems2[1::2, 0::2, 0::2, 1] -= 1
    elems2[0::2, 1::2, 0::2, 1] -= 1
    elems2[0::2, 0::2, 1::2, 1] -= 1
    elems2[1::2, 1::2, 1::2, 1] -= 1

    elems2[1::2, 0::2, 0::2, 2] += 1
    elems2[0::2, 1::2, 0::2, 2] += 1
    elems2[0::2, 0::2, 1::2, 2] += 1
    elems2[1::2, 1::2, 1::2, 2] += 1

    elems2[1::2, 0::2, 0::2, 3] -= 1
    elems2[0::2, 1::2, 0::2, 3] -= 1
    elems2[0::2, 0::2, 1::2, 3] -= 1
    elems2[1::2, 1::2, 1::2, 3] -= 1

    # Tetrahedron 3:
    # [
    # i   + nx * (j+1) + nx*ny * k,
    # i   + nx * j     + nx*ny * (k+1),
    # i   + nx * (j+1) + nx*ny * (k+1),
    # i+1 + nx * (j+1) + nx*ny * (k+1)
    # ]
    # elems3 = numpy.stack([
    #     a + nx,
    #     a + nx*ny,
    #     a + nx + nx*ny,
    #     a + 1 + nx + nx*ny
    #     ]).T
    elems3 = numpy.concatenate(
        [
            a[..., None] + nx,
            a[..., None] + nx * ny,
            a[..., None] + nx + nx * ny,
            a[..., None] + 1 + nx + nx * ny,
        ],
        axis=3,
    )

    # Every other element cube:
    # [
    # i+1 + nx * (j+1) + nx*ny * k,
    # i+1 + nx * j     + nx*ny * (k+1),
    # i+1 + nx * (j+1) + nx*ny * (k+1),
    # i   + nx * (j+1) + nx*ny * (k+1)
    # ]
    elems3[1::2, 0::2, 0::2, 0] += 1
    elems3[0::2, 1::2, 0::2, 0] += 1
    elems3[0::2, 0::2, 1::2, 0] += 1
    elems3[1::2, 1::2, 1::2, 0] += 1

    elems3[1::2, 0::2, 0::2, 1] += 1
    elems3[0::2, 1::2, 0::2, 1] += 1
    elems3[0::2, 0::2, 1::2, 1] += 1
    elems3[1::2, 1::2, 1::2, 1] += 1

    elems3[1::2, 0::2, 0::2, 2] += 1
    elems3[0::2, 1::2, 0::2, 2] += 1
    elems3[0::2, 0::2, 1::2, 2] += 1
    elems3[1::2, 1::2, 1::2, 2] += 1

    elems3[1::2, 0::2, 0::2, 3] -= 1
    elems3[0::2, 1::2, 0::2, 3] -= 1
    elems3[0::2, 0::2, 1::2, 3] -= 1
    elems3[1::2, 1::2, 1::2, 3] -= 1

    # Tetrahedron 4:
    # [
    # i+1 + nx * j     + nx*ny * k,
    # i   + nx * j     + nx*ny * (k+1),
    # i+1 + nx * (j+1) + nx*ny * (k+1),
    # i+1 + nx * j     + nx*ny * (k+1)
    # ]
    # elems4 = numpy.stack([
    #     a + 1,
    #     a + nx*ny,
    #     a + 1 + nx + nx*ny,
    #     a + 1 + nx*ny
    #     ]).T
    elems4 = numpy.concatenate(
        [
            a[..., None] + 1,
            a[..., None] + nx * ny,
            a[..., None] + 1 + nx + nx * ny,
            a[..., None] + 1 + nx * ny,
        ],
        axis=3,
    )

    # Every other element cube:
    # [
    # i   + nx * j     + nx*ny * k,
    # i+1 + nx * j     + nx*ny * (k+1),
    # i   + nx * (j+1) + nx*ny * (k+1),
    # i   + nx * j     + nx*ny * (k+1)
    # ]
    elems4[1::2, 0::2, 0::2, 0] -= 1
    elems4[0::2, 1::2, 0::2, 0] -= 1
    elems4[0::2, 0::2, 1::2, 0] -= 1
    elems4[1::2, 1::2, 1::2, 0] -= 1

    elems4[1::2, 0::2, 0::2, 1] += 1
    elems4[0::2, 1::2, 0::2, 1] += 1
    elems4[0::2, 0::2, 1::2, 1] += 1
    elems4[1::2, 1::2, 1::2, 1] += 1

    elems4[1::2, 0::2, 0::2, 2] -= 1
    elems4[0::2, 1::2, 0::2, 2] -= 1
    elems4[0::2, 0::2, 1::2, 2] -= 1
    elems4[1::2, 1::2, 1::2, 2] -= 1

    elems4[1::2, 0::2, 0::2, 3] -= 1
    elems4[0::2, 1::2, 0::2, 3] -= 1
    elems4[0::2, 0::2, 1::2, 3] -= 1
    elems4[1::2, 1::2, 1::2, 3] -= 1

    elems = numpy.vstack(
        [
            elems0.reshape(-1, 4),
            elems1.reshape(-1, 4),
            elems2.reshape(-1, 4),
            elems3.reshape(-1, 4),
            elems4.reshape(-1, 4),
        ]
    )

    return nodes, elems
1034900
def model_fn(features, labels, mode, params):
  """"""
  tf.logging.info("features = %s labels = %s mode = %s params=%s" %
                  (features, labels, mode, params))
  global_step = tf.train.get_global_step()
  graph = mtf.Graph()
  mesh = mtf.Mesh(graph, "my_mesh")
  logits, loss = mnist_model(features, labels, mesh)
  mesh_shape = mtf.convert_to_shape(FLAGS.mesh_shape)
  layout_rules = mtf.convert_to_layout_rules(FLAGS.layout)
  mesh_size = mesh_shape.size
  mesh_devices = [""] * mesh_size
  mesh_impl = mtf.placement_mesh_impl.PlacementMeshImpl(
      mesh_shape, layout_rules, mesh_devices)

  if mode == tf.estimator.ModeKeys.TRAIN:
    var_grads = mtf.gradients(
        [loss], [v.outputs[0] for v in graph.trainable_variables])
    optimizer = mtf.optimize.AdafactorOptimizer()
    update_ops = optimizer.apply_grads(var_grads, graph.trainable_variables)

  lowering = mtf.Lowering(graph, {mesh: mesh_impl})
  restore_hook = mtf.MtfRestoreHook(lowering)

  tf_logits = lowering.export_to_tf_tensor(logits)
  if mode != tf.estimator.ModeKeys.PREDICT:
    tf_loss = lowering.export_to_tf_tensor(loss)
    tf.summary.scalar("loss", tf_loss)

  if mode == tf.estimator.ModeKeys.TRAIN:
    tf_update_ops = [lowering.lowered_operation(op) for op in update_ops]
    tf_update_ops.append(tf.assign_add(global_step, 1))
    train_op = tf.group(tf_update_ops)
    saver = tf.train.Saver(
        tf.global_variables(),
        sharded=True,
        max_to_keep=10,
        keep_checkpoint_every_n_hours=2,
        defer_build=False, save_relative_paths=True)
    tf.add_to_collection(tf.GraphKeys.SAVERS, saver)
    saver_listener = mtf.MtfCheckpointSaverListener(lowering)
    saver_hook = tf.train.CheckpointSaverHook(
        FLAGS.model_dir,
        save_steps=1000,
        saver=saver,
        listeners=[saver_listener])

    accuracy = tf.metrics.accuracy(
        labels=labels, predictions=tf.argmax(tf_logits, axis=1))

    # Name tensors to be logged with LoggingTensorHook.
    tf.identity(tf_loss, "cross_entropy")
    tf.identity(accuracy[1], name="train_accuracy")

    # Save accuracy scalar to Tensorboard output.
    tf.summary.scalar("train_accuracy", accuracy[1])

    # restore_hook must come before saver_hook
    return tf.estimator.EstimatorSpec(
        tf.estimator.ModeKeys.TRAIN, loss=tf_loss, train_op=train_op,
        training_chief_hooks=[restore_hook, saver_hook])

  if mode == tf.estimator.ModeKeys.PREDICT:
    predictions = {
        "classes": tf.argmax(tf_logits, axis=1),
        "probabilities": tf.nn.softmax(tf_logits),
    }
    return tf.estimator.EstimatorSpec(
        mode=tf.estimator.ModeKeys.PREDICT,
        predictions=predictions,
        prediction_hooks=[restore_hook],
        export_outputs={
            "classify": tf.estimator.export.PredictOutput(predictions)
        })
  if mode == tf.estimator.ModeKeys.EVAL:
    return tf.estimator.EstimatorSpec(
        mode=tf.estimator.ModeKeys.EVAL,
        loss=tf_loss,
        evaluation_hooks=[restore_hook],
        eval_metric_ops={
            "accuracy":
            tf.metrics.accuracy(
                labels=labels, predictions=tf.argmax(tf_logits, axis=1)),
        })
111299
def mesh(self):
        """"""
        triangles = np.empty((self.f.shape[0], 4))
        triangles[:, -3:] = self.f
        triangles[:, 0] = 3
        return vtki.PolyData(self.v, triangles, deep=False)
16070
def create_from_mesh_and_lines(cls, mesh, lines):
        '''
        

        '''
        mesh_with_lines = mesh.copy()
        mesh_with_lines.add_lines(lines)
        return mesh_with_lines
1358762
def background_mesh_ma(self):
        

        if len(self._bkg1d) == self.nboxes:
            return self.background_mesh
        else:
            return self._make_2d_array(self._bkg1d)
220916
def to_tensor(self):
    """"""
    a_shape = shape_list(self.a)
    b_shape = shape_list(self.b)
    inner_dim = b_shape[1]
    result_dim = b_shape[0]
    flat_a = tf.reshape(self.a, [-1, inner_dim])
    product = tf.matmul(flat_a, self.b, transpose_b=True)
    product_shape = a_shape[:-1] + [result_dim]
    product = tf.reshape(product, product_shape)
    product.set_shape(self.a.get_shape().as_list()[:-1] +
                      [self.b.get_shape()[0]])
    return product
519836
def cell_scalar(mesh, name):
    
    vtkarr = mesh.GetCellData().GetArray(name)
    if vtkarr:
        if isinstance(vtkarr, vtk.vtkBitArray):
            vtkarr = vtk_bit_array_to_char(vtkarr)
        return vtk_to_numpy(vtkarr)
787495
def get_mesh(self, body_name, **kwargs):
        """"""
        body = self.bodies[body_name]
        vertices = body['v']
        normals = body['vn'] if 'vn' in body else None
        texcoords = body['vt'] if 'vt' in body else None
        mesh = Mesh.from_incomplete_data(vertices=vertices, normals=normals, texcoords=texcoords, **kwargs)

        uniforms = kwargs['uniforms'] if 'uniforms' in kwargs else {}
        if 'material' in body:
            material_props = {self.material_property_map[key]: value for key, value in iteritems(body['material'])}
            for key, value in iteritems(material_props):
                if isinstance(value, str):
                    if key == 'map_Kd':
                        if not value in self.textures:
                            self.textures[value] = Texture.from_image(value)
                        mesh.textures.append(self.textures[value])
                    else:
                        setattr(mesh, key, value)
                elif hasattr(value, '__len__'):  # iterable materials
                    mesh.uniforms[key] = value
                elif key in ['d', 'illum']:  # integer materials
                    mesh.uniforms[key] = value
                elif key in ['spec_weight', 'Ni']:  # float materials: should be specially converted to float if not already done.
                    mesh.uniforms[key] = float(value)
                else:
                    print('Warning: Not applying uniform {}: {}'.format(key, value))
        return mesh
840889
def __init_from_np2d(self, mat, params_str, ref_dataset):
        """"""
        if len(mat.shape) != 2:
            raise ValueError('Input numpy.ndarray must be 2 dimensional')

        self.handle = ctypes.c_void_p()
        if mat.dtype == np.float32 or mat.dtype == np.float64:
            data = np.array(mat.reshape(mat.size), dtype=mat.dtype, copy=False)
        else:
            # change non-float data to float data, need to copy
            data = np.array(mat.reshape(mat.size), dtype=np.float32)

        ptr_data, type_ptr_data, _ = c_float_array(data)
        _safe_call(_LIB.LGBM_DatasetCreateFromMat(
            ptr_data,
            ctypes.c_int(type_ptr_data),
            ctypes.c_int(mat.shape[0]),
            ctypes.c_int(mat.shape[1]),
            ctypes.c_int(C_API_IS_ROW_MAJOR),
            c_str(params_str),
            ref_dataset,
            ctypes.byref(self.handle)))
        return self
861515
def tensor_layout(self, tensor_shape, mesh_shape):
    
    ret = [self.tensor_dimension_to_mesh_axis(d, mesh_shape)
           for d in tensor_shape]
    not_nones = [a for a in ret if a is not None]
    if len(not_nones) != len(set(not_nones)):
      raise ValueError(
          "Two Tensor Dimensions may not map to the same Mesh Dimension:"
          " layout=%s tensor_shape=%s mesh_shape=%s " %
          (self, tensor_shape, mesh_shape))
    return TensorLayout(ret)
307821
function centerMesh (mesh) {
  var bb = boundingBox(mesh.positions)

  var _translate = [
    -0.5 * (bb[0][0] + bb[1][0]),
    -0.5 * (bb[0][1] + bb[1][1]),
    -0.5 * (bb[0][2] + bb[1][2])
  ]
  var translate = mat4.create()
  mat4.translate(translate, translate, _translate)
  mesh.positions = tform(mesh.positions, translate)
}
323065
def combine_slices(self, slices, tensor_shape, device=None):
    
    if tensor_shape.ndims == 0:
      return slices[0]

    ret = slices[:]
    tensor_layout = self.tensor_layout(tensor_shape)
    for mesh_dim, tensor_axis in zip(
        self.shape, tensor_layout.mesh_axis_to_tensor_axis(self.ndims)):
      slice_size = len(ret) // mesh_dim.size
      if tensor_axis is None:
        ret = ret[:slice_size]
      else:
        if device:
          devices = [device] * slice_size
        else:
          devices = [ret[i].device for i in xrange(slice_size)]
        concat_inputs = []
        for i in xrange(slice_size):
          concat_inputs.append(
              [ret[i + slice_size * j] for j in xrange(mesh_dim.size)])
        ret = parallel(
            devices, tf.concat, concat_inputs,
            axis=[tensor_axis] * len(devices))
    assert len(ret) == 1
    return ret[0]
989772
def mesh_to_BVH(mesh):
    
    bvh = fcl.BVHModel()
    bvh.beginModel(num_tris_=len(mesh.faces),
                   num_vertices_=len(mesh.vertices))
    bvh.addSubModel(verts=mesh.vertices,
                    triangles=mesh.faces)
    bvh.endModel()
    return bvh