Export ``PointCloud`` to PLY file for viewing in MeshLab.
194575
def write_ply(self, output_file):
        """"""
        points = np.hstack([self.coordinates, self.colors])
        with open(output_file, 'w') as outfile:
            outfile.write(self.ply_header.format(
                                            vertex_count=len(self.coordinates)))
            np.savetxt(outfile, points, '%f %f %f %d %d %d')
1350558
def create_ellipse_mesh(points,**kwargs):
    """"""
    import plotly.graph_objs as go
    x,y,z = points.T
    return (go.Mesh3d(x=x,y=y,z=z,**kwargs),
            go.Scatter3d(x=x, y=y, z=z,
                         marker=dict(size=0.01),
                         line=dict(width=2,color='#000000'),
                         showlegend=False,
                         hoverinfo='none'
            )
    )
753378
def to_contour(grid_size=@npoints)
		m = Matrix.alloc(grid_size, grid_size)
		raise TypeError("Must be 3d data") unless @gridpoints.shape[1] == 2
# 			p @gridpoints.shape
# 			p @gridpoints
		xmax, xmin = @gridpoints.col(0).max, @gridpoints.col(0).min
		ymax, ymin = @gridpoints.col(1).max, @gridpoints.col(1).min
		p 'x', xmax, 'y', ymax
		xvec = GSL::Vector.alloc((0...grid_size).to_a) * (xmax - xmin) / (grid_size - 1.0).to_f + xmin
		yvec = GSL::Vector.alloc((0...grid_size).to_a) * (ymax - ymin) / (grid_size - 1.0).to_f + ymin	
		p 'x', xvec.max, 'y', yvec.max

		for i in 0...grid_size
			for j in 0...grid_size
# 					p xvec[i], yvec[j]
				m[i,j] = eval(xvec[i], yvec[j])
			end
		end
		p 'm', m.max
		Contour.alloc(xvec, yvec, m)
	end
1134750
def export_mesh(vertices, triangles, filename, mesh_name="mcubes_mesh"):
    
    
    import collada
    
    mesh = collada.Collada()
    
    vert_src = collada.source.FloatSource("verts-array", vertices, ('X','Y','Z'))
    geom = collada.geometry.Geometry(mesh, "geometry0", mesh_name, [vert_src])
    
    input_list = collada.source.InputList()
    input_list.addInput(0, 'VERTEX', "#verts-array")
    
    triset = geom.createTriangleSet(np.copy(triangles), input_list, "")
    geom.primitives.append(triset)
    mesh.geometries.append(geom)
    
    geomnode = collada.scene.GeometryNode(geom, [])
    node = collada.scene.Node(mesh_name, children=[geomnode])
    
    myscene = collada.scene.Scene("mcubes_scene", [node])
    mesh.scenes.append(myscene)
    mesh.scene = myscene
    
    mesh.write(filename)
1251590
public static void dumpTexCoords(AiMesh mesh, int coords) {
        if (!mesh.hasTexCoords(coords)) {
            System.out.println("mesh has no texture coordinate set " + coords);
            return;
        }
        
        for (int i = 0; i < mesh.getNumVertices(); i++) {
            int numComponents = mesh.getNumUVComponents(coords);
            System.out.print("[" + mesh.getTexCoordU(i, coords));
            
            if (numComponents > 1) {
                System.out.print(", " + mesh.getTexCoordV(i, coords));
            }
            
            if (numComponents > 2) {
                System.out.print(", " + mesh.getTexCoordW(i, coords));
            }
            
            System.out.println("]");
        }
    }
253326
def export_frame_coordinates(topology, trajectory, nframe, output=None):
    
    if output is None:
        basename, ext = os.path.splitext(trajectory)
        output = '{}.frame{}.inpcrd'.format(basename, nframe)

    # ParmEd sometimes struggles with certain PRMTOP files
    if os.path.splitext(topology)[1] in ('.top', '.prmtop'):
        top = AmberPrmtopFile(topology)
        mdtop = mdtraj.Topology.from_openmm(top.topology)
        traj = mdtraj.load_frame(trajectory, int(nframe), top=mdtop)
        structure = parmed.openmm.load_topology(top.topology, system=top.createSystem())
        structure.box_vectors = top.topology.getPeriodicBoxVectors()

    else:  # standard protocol (the topology is loaded twice, though)
        traj = mdtraj.load_frame(trajectory, int(nframe), top=topology)
        structure = parmed.load_file(topology)

    structure.positions = traj.openmm_positions(0)

    if traj.unitcell_vectors is not None:  # if frame provides box vectors, use those
        structure.box_vectors = traj.openmm_boxes(0)

    structure.save(output, overwrite=True)
234951
def save_graph_to_file(graph_file_name, module_spec, class_count):
  """"""
  sess, _, _, _, _, _ = build_eval_session(module_spec, class_count)
  graph = sess.graph

  output_graph_def = tf.graph_util.convert_variables_to_constants(
      sess, graph.as_graph_def(), [FLAGS.final_tensor_name])

  with tf.gfile.GFile(graph_file_name, 'wb') as f:
    f.write(output_graph_def.SerializeToString())
1045906
def _to_point(dims):
  """"""
  assert dims

  if isinstance(dims, (tuple, list)):
    if len(dims) != 2:
      raise ValueError(
          "A two element tuple or list is expected here, got {}.".format(dims))
    else:
      width = int(dims[0])
      height = int(dims[1])
      if width <= 0 or height <= 0:
        raise ValueError("Must specify +ve dims, got {}.".format(dims))
      else:
        return point.Point(width, height)
  else:
    size = int(dims)
    if size <= 0:
      raise ValueError(
          "Must specify a +ve value for size, got {}.".format(dims))
    else:
      return point.Point(size, size)
1024457
def mesh(faces, coordinates, meta_data=None, properties=None):
    '''
    
    '''
    return Mesh(faces, coordinates, meta_data=meta_data, properties=properties)
21619
def write(self, filename="mesh.vtk", binary=True):
        
        import vtkplotter.vtkio as vtkio

        return vtkio.write(self, filename, binary)
301078
def export_stl_ascii(mesh):
    

    # move all the data that's going into the STL file into one array
    blob = np.zeros((len(mesh.faces), 4, 3))
    blob[:, 0, :] = mesh.face_normals
    blob[:, 1:, :] = mesh.triangles

    # create a lengthy format string for the data section of the file
    format_string = 'facet normal {} {} {}\nouter loop\n'
    format_string += 'vertex {} {} {}\n' * 3
    format_string += 'endloop\nendfacet\n'
    format_string *= len(mesh.faces)

    # concatenate the header, data, and footer
    export = 'solid \n'
    export += format_string.format(*blob.reshape(-1))
    export += 'endsolid'

    return export
444907
def export(app, local, no_scrub):
    """"""
    log(header, chevrons=False)
    data.export(str(app), local=local, scrub_pii=(not no_scrub))
639741
def to_mesh(self, dist_thresh=0.01):
        
        # init vertex and triangle buffers
        vertices = []
        triangles = []
        vertex_indices = -1 * np.ones([self.height, self.width]).astype(np.int32)
        
        for i in range(self.height-1):
            for j in range(self.width-1):
                # read corners of square
                v0 = self.data[i,j,:]
                v1 = self.data[i,j+1,:]
                v2 = self.data[i+1,j,:]
                v3 = self.data[i+1,j+1,:]

                # check distances
                d01 = np.abs(v0[2] - v1[2])
                d02 = np.abs(v0[2] - v2[2])
                d03 = np.abs(v0[2] - v3[2])
                d13 = np.abs(v1[2] - v3[2])
                d23 = np.abs(v2[2] - v3[2])

                # add tri 1
                if max(d01, d03, d13) < dist_thresh:
                    # add vertices
                    if vertex_indices[i,j] == -1:
                        vertices.append(v0)
                        vertex_indices[i,j] = len(vertices)-1
                    if vertex_indices[i,j+1] == -1:
                        vertices.append(v1)
                        vertex_indices[i,j+1] = len(vertices)-1
                    if vertex_indices[i+1,j+1] == -1:
                        vertices.append(v3)
                        vertex_indices[i+1,j+1] = len(vertices)-1
                
                    # add tri
                    i0 = vertex_indices[i,j]
                    i1 = vertex_indices[i,j+1]
                    i3 = vertex_indices[i+1,j+1]
                    triangles.append([i0, i1, i3])

                # add tri 2
                if max(d01, d03, d23) < dist_thresh:
                    # add vertices
                    if vertex_indices[i,j] == -1:
                        vertices.append(v0)
                        vertex_indices[i,j] = len(vertices)-1
                    if vertex_indices[i+1,j] == -1:
                        vertices.append(v2)
                        vertex_indices[i+1,j] = len(vertices)-1
                    if vertex_indices[i+1,j+1] == -1:
                        vertices.append(v3)
                        vertex_indices[i+1,j+1] = len(vertices)-1
                
                    # add tri
                    i0 = vertex_indices[i,j]
                    i2 = vertex_indices[i+1,j]
                    i3 = vertex_indices[i+1,j+1]
                    triangles.append([i0, i3, i2])

        # return trimesh
        import trimesh
        mesh = trimesh.Trimesh(vertices, triangles)
        return mesh
1344123
def surface_to_image(surface):
    """"""
    from IPython.display import Image
    buf = BytesIO()
    surface.write_to_png(buf)
    data = buf.getvalue()
    buf.close()
    return Image(data=data)
535809
def ply2gii(in_file, metadata, out_file=None):
    """"""
    from pathlib import Path
    from numpy import eye
    from nibabel.gifti import (
        GiftiMetaData, GiftiCoordSystem, GiftiImage, GiftiDataArray,
    )
    from pyntcloud import PyntCloud

    in_file = Path(in_file)
    surf = PyntCloud.from_file(str(in_file))

    # Update centroid metadata
    metadata.update(
        zip(('SurfaceCenterX', 'SurfaceCenterY', 'SurfaceCenterZ'),
            ['%.4f' % c for c in surf.centroid])
    )

    # Prepare data arrays
    da = (
        GiftiDataArray(
            data=surf.xyz.astype('float32'),
            datatype='NIFTI_TYPE_FLOAT32',
            intent='NIFTI_INTENT_POINTSET',
            meta=GiftiMetaData.from_dict(metadata),
            coordsys=GiftiCoordSystem(xform=eye(4), xformspace=3)),
        GiftiDataArray(
            data=surf.mesh.values,
            datatype='NIFTI_TYPE_INT32',
            intent='NIFTI_INTENT_TRIANGLE',
            coordsys=None))
    surfgii = GiftiImage(darrays=da)

    if out_file is None:
        out_file = fname_presuffix(
            in_file.name, suffix='.gii', use_ext=False, newpath=str(Path.cwd()))

    surfgii.to_filename(str(out_file))
    return out_file
1134862
def export_dxf(path, layers=None):
    

    def format_points(points,
                      as_2D=False,
                      increment=True):
        """
        Format points into DXF- style point string.

        Parameters
        -----------
        points : (n,2) or (n,3) float
          Points in space
        as_2D : bool
          If True only output 2 points per vertex
        increment : bool
          If True increment group code per point
          Example:
            [[X0, Y0, Z0], [X1, Y1, Z1]]
          Result, new lines replaced with spaces:
            True  -> 10 X0 20 Y0 30 Z0 11 X1 21 Y1 31 Z1
            False -> 10 X0 20 Y0 30 Z0 10 X1 20 Y1 30 Z1

        Returns
        -----------
        packed : str
          Points formatted with group code
        """
        points = np.asanyarray(points, dtype=np.float64)
        # get points in 3D
        three = util.stack_3D(points)
        if increment:
            group = np.tile(
                np.arange(len(three), dtype=np.int).reshape((-1, 1)),
                (1, 3))
        else:
            group = np.zeros((len(three), 3), dtype=np.int)
        group += [10, 20, 30]

        if as_2D:
            group = group[:, :2]
            three = three[:, :2]

        packed = '\n'.join('{:d}\n{:.12f}'.format(g, v)
                           for g, v in zip(group.reshape(-1),
                                           three.reshape(-1)))

        return packed

    def entity_info(entity):
        """
        Pull layer, color, and name information about an entity

        Parameters
        -----------
        entity : entity object
          Source entity to pull metadata

        Returns
        ----------
        subs : dict
          Has keys 'COLOR', 'LAYER', 'NAME'
        """
        subs = {'COLOR': 255,  # default is ByLayer
                'LAYER': 0,
                'NAME': str(id(entity))[:16]}

        if hasattr(entity, 'color'):
            # all colors must be integers between 0-255
            color = str(entity.color)
            if str.isnumeric(color):
                subs['COLOR'] = int(color) % 256

        if hasattr(entity, 'layer'):
            subs['LAYER'] = str(entity.layer)

        return subs

    def convert_line(line, vertices):
        """
        Convert an entity to a discrete polyline

        Parameters
        -------------
        line : entity
          Entity which has 'e.discrete' method
        vertices : (n, 2) float
          Vertices in space

        Returns
        -----------
        as_dxf : str
          Entity exported as a DXF
        """
        # get a discrete representation of entity
        points = line.discrete(vertices)
        # if one or fewer points return nothing
        if len(points) <= 1:
            return ''

        # generate a substitution dictionary for template
        subs = entity_info(line)
        subs['POINTS'] = format_points(points,
                                       as_2D=True,
                                       increment=False)
        subs['TYPE'] = 'LWPOLYLINE'
        subs['VCOUNT'] = len(points)
        # 1 is closed
        # 0 is default (open)
        subs['FLAG'] = int(bool(line.closed))

        result = TEMPLATES['line'].substitute(subs)
        return result

    def convert_arc(arc, vertices):
        info = arc.center(vertices)
        subs = entity_info(arc)

        center = info['center']
        if len(center) == 2:
            center = np.append(center, 0.0)
        data = '10\n{:.12f}\n20\n{:.12f}\n30\n{:.12f}'.format(*center)
        data += '\n40\n{:.12f}'.format(info['radius'])

        if arc.closed:
            subs['TYPE'] = 'CIRCLE'
        else:
            subs['TYPE'] = 'ARC'
            # an arc is the same as a circle, with an added start
            # and end angle field
            data += '\n100\nAcDbArc'
            data += '\n50\n{:.12f}\n51\n{:.12f}'.format(
                *np.degrees(info['angles']))
        subs['DATA'] = data

        result = TEMPLATES['arc'].substitute(subs)

        return result

    def convert_bspline(spline, vertices):
        # points formatted with group code
        points = format_points(vertices[spline.points],
                               increment=False)

        # (n,) float knots, formatted with group code
        knots = ('40\n{:.12f}\n' * len(spline.knots)
                 ).format(*spline.knots)[:-1]

        # bit coded
        flags = {'closed': 1,
                 'periodic': 2,
                 'rational': 4,
                 'planar': 8,
                 'linear': 16}

        flag = flags['planar']
        if spline.closed:
            flag = flag | flags['closed']

        normal = [0.0, 0.0, 1.0]
        n_code = [210, 220, 230]
        n_str = '\n'.join('{:d}\n{:.12f}'.format(i, j)
                          for i, j in zip(n_code, normal))

        subs = entity_info(spline)
        subs.update({'TYPE': 'SPLINE',
                     'POINTS': points,
                     'KNOTS': knots,
                     'NORMAL': n_str,
                     'DEGREE': 3,
                     'FLAG': flag,
                     'FCOUNT': 0,
                     'KCOUNT': len(spline.knots),
                     'PCOUNT': len(spline.points)})
        # format into string template
        result = TEMPLATES['bspline'].substitute(subs)

        return result

    def convert_text(txt, vertices):
        """
        Convert a Text entity to DXF string.
        """
        sub = entity_info(txt)

        # get the origin point of the text
        sub['ORIGIN'] = format_points(vertices[[txt.origin]],
                                      increment=False)
        # rotation angle in degrees
        sub['ANGLE'] = np.degrees(txt.angle(vertices))
        # actual string of text with spaces escaped
        sub['TEXT'] = txt.text.replace(' ', _SAFESPACE)
        # height of text
        sub['HEIGHT'] = txt.height

        return TEMPLATES['text'].substitute(sub)

    def convert_generic(entity, vertices):
        """
        For entities we don't know how to handle, return their
        discrete form as a polyline
        """
        return convert_line(entity, vertices)

    # make sure we're not losing a ton of
    # precision in the string conversion
    np.set_printoptions(precision=12)
    # trimesh entity to DXF entity converters
    conversions = {'Line': convert_line,
                   'Text': convert_text,
                   'Arc': convert_arc,
                   'Bezier': convert_generic,
                   'BSpline': convert_bspline}
    collected = []
    for e, layer in zip(path.entities, path.layers):
        name = type(e).__name__
        # only export specified layers
        if layers is not None:
            if layer not in layers:
                continue
        if name in conversions:
            converted = conversions[name](e, path.vertices).strip()
            # only save if we converted something
            if len(converted) > 0:
                collected.append(converted)
        else:
            log.debug('Entity type %s not exported!', name)

    entities_str = '\n'.join(collected)

    hsub = {'BOUNDS_MIN': format_points([path.bounds[0]]),
            'BOUNDS_MAX': format_points([path.bounds[1]]),
            'LUNITS': '1'}
    if path.units in _UNITS_TO_DXF:
        hsub['LUNITS'] = _UNITS_TO_DXF[path.units]

    # sections of the DXF
    header = TEMPLATES['header'].substitute(hsub)
    # entities section
    entities = TEMPLATES['entities'].substitute({
        'ENTITIES': entities_str})
    footer = TEMPLATES['footer'].substitute()

    # filter out empty sections
    # random whitespace causes AutoCAD to fail to load
    # although Draftsight, LibreCAD, and Inkscape don't care
    # what a giant legacy piece of shit
    # strip out all leading and trailing whitespace
    sections = [i.strip() for i in [header,
                                    entities,
                                    footer]
                if len(i) > 0]

    blob = '\n'.join(sections).replace(_SAFESPACE, ' ')

    # run additional self- checks
    if tol.strict:
        # check that every line pair is (group code, value)
        lines = str.splitlines(str(blob))

        # should be even number of lines
        assert (len(lines) % 2) == 0

        # group codes should all be convertible to int and positive
        assert all(int(i) >= 0 for i in lines[::2])

    return blob
93702
def MeshPoints(*inputobj, **options):
    
    r = options.pop("r", 5)
    c = options.pop("c", "gray")
    alpha = options.pop("alpha", 1)

    mesh, u = _inputsort(inputobj)
    plist = mesh.coordinates()
    if u:
        u_values = np.array([u(p) for p in plist])
    if len(plist[0]) == 2:  # coords are 2d.. not good..
        plist = np.insert(plist, 2, 0, axis=1)  # make it 3d
    if len(plist[0]) == 1:  # coords are 1d.. not good..
        plist = np.insert(plist, 1, 0, axis=1)  # make it 3d
        plist = np.insert(plist, 2, 0, axis=1)

    actor = shapes.Points(plist, r=r, c=c, alpha=alpha)

    actor.mesh = mesh
    if u:
        actor.u = u
        if len(u_values.shape) == 2:
            if u_values.shape[1] in [2, 3]:  # u_values is 2D or 3D
                actor.u_values = u_values
                dispsizes = utils.mag(u_values)
        else:  # u_values is 1D
            dispsizes = u_values
        actor.addPointScalars(dispsizes, "u_values")
    return actor