dump vtkjs normal vectors
7677
def dump_normals(dataset_dir, data_dir, dataset, root=None, compress=True):
    """"""
    if root is None:
        root = {}
    normals = dataset.GetPointData().GetNormals()
    if normals:
        dumped_array = dump_data_array(dataset_dir, data_dir, normals, {}, compress)
        root['pointData']['activeNormals'] = len(root['pointData']['arrays'])
        root['pointData']['arrays'].append({'data': dumped_array})
294722
def _generate_plane(normal, origin):
    
    plane = vtk.vtkPlane()
    plane.SetNormal(normal[0], normal[1], normal[2])
    plane.SetOrigin(origin[0], origin[1], origin[2])
    return plane
54272
def vec2ang(vectors, lonlat=False):
    """"""
    x, y, z = vectors.transpose()
    rep_car = CartesianRepresentation(x, y, z)
    rep_sph = rep_car.represent_as(UnitSphericalRepresentation)
    return _lonlat_to_healpy(rep_sph.lon.ravel(), rep_sph.lat.ravel(), lonlat=lonlat)
1364189
def from_arrays(cls, name, verts, normals, n_verts=3):

        """"""

        # Put header in string
        wavefront_str = "o {name}\n".format(name=name)

        # Write Vertex data from vert_dict
        for vert in verts:
            wavefront_str += "v {0} {1} {2}\n".format(*vert)

        # Write (false) UV Texture data
        wavefront_str += "vt 1.0 1.0\n"

        for norm in normals:
            wavefront_str += "vn {0} {1} {2}\n".format(*norm)


        # Write Face Indices (1-indexed)
        for wall_idx, vert_indices in enumerate(grouper(n_verts, range(1, len(verts) + 1))):
            face_str = 'f '
            for idx in vert_indices:
                face_str += "{v}/1/{n} ".format(v=idx, n=wall_idx + 1)
            wavefront_str += face_str + '\n'

        return WavefrontWriter(string=wavefront_str)
555320
function DumpInternals() {
    for (let ck in exports.globalKCState.controllers) {
        console.log("============================================");
        console.log(`Controller on path ${exports.globalKCState.controllers[ck].path} built from Class ${exports.globalKCState.controllers[ck].ctr.name}`);
        console.log("With Methods:");
        for (let mk in exports.globalKCState.controllers[ck].methods) {
            let m = exports.globalKCState.controllers[ck].methods[mk];
            console.log(`== ${mk} ==`);
            console.log(m);
            console.log("");
        }
    }
}
1067867
def make_nd_vec(v, nd=None, t=None, norm=False):
    

    # Imports
    import numpy as np
    from scipy import linalg as spla

    # Reduce the input to the extent possible
    out_v = np.array(v, dtype=t).squeeze()

    # Confirm vector form
    if not len(out_v.shape) == 1:
        raise ValueError("'v' is not reducible to a vector.")
    ## end if

    # If indicated, confirm dimensionality
    if nd and not out_v.shape[0] == nd:
        raise ValueError("'v' dimension is " + str(out_v.shape[0]) +
                ", not " + str(nd))
    ## end if

    # Normalize, if indicated
    if norm:
        out_v = out_v / spla.norm(out_v)
    ## end if

    # Return result
    return out_v
18176
def _dump_multilinestring(obj, big_endian, meta):
    
    coords = obj['coordinates']
    vertex = coords[0][0]
    num_dims = len(vertex)

    wkb_string, byte_fmt, byte_order = _header_bytefmt_byteorder(
        'MultiLineString', num_dims, big_endian, meta
    )

    ls_type = _WKB[_INT_TO_DIM_LABEL.get(num_dims)]['LineString']
    if big_endian:
        ls_type = BIG_ENDIAN + ls_type
    else:
        ls_type = LITTLE_ENDIAN + ls_type[::-1]

    # append the number of linestrings
    wkb_string += struct.pack('%sl' % byte_order, len(coords))

    for linestring in coords:
        wkb_string += ls_type
        # append the number of vertices in each linestring
        wkb_string += struct.pack('%sl' % byte_order, len(linestring))
        for vertex in linestring:
            wkb_string += struct.pack(byte_fmt, *vertex)

    return wkb_string
1226185
def write_grid_to_vtk(fname, nodes, edges, node_flag=None, edge_flag=None):
    

    if node_flag is None:
        node_flag = np.ones([nodes.shape[0]], dtype=np.bool)
    if edge_flag is None:
        edge_flag = np.ones([edges.shape[0]], dtype=np.bool)
    nodes = make_nodes_3d(nodes)
    f = open(fname, "w")

    f.write("# vtk DataFile Version 2.6\n")
    f.write("output file\nASCII\nDATASET UNSTRUCTURED_GRID\n")

    idxs = nm.where(node_flag > 0)[0]
    nnd = len(idxs)
    aux = -nm.ones(node_flag.shape, dtype=nm.int32)
    aux[idxs] = nm.arange(nnd, dtype=nm.int32)
    f.write("\nPOINTS %d float\n" % nnd)
    for ndi in idxs:
        f.write("%.6f %.6f %.6f\n" % tuple(nodes[ndi, :]))

    idxs = nm.where(edge_flag > 0)[0]
    ned = len(idxs)
    f.write("\nCELLS %d %d\n" % (ned, ned * 3))
    for edi in idxs:
        f.write("2 %d %d\n" % tuple(aux[edges[edi, :]]))

    f.write("\nCELL_TYPES %d\n" % ned)
    for edi in idxs:
        f.write("3\n")
55033
def transform(self, trans):
        
        if isinstance(trans, vtk.vtkMatrix4x4):
            t = vtki.trans_from_matrix(trans)
        elif isinstance(trans, vtk.vtkTransform):
            t = vtki.trans_from_matrix(trans.GetMatrix())
        elif isinstance(trans, np.ndarray):
            if trans.shape[0] != 4 or trans.shape[1] != 4:
                raise Exception('Transformation array must be 4x4')
            t = trans
        else:
            raise TypeError('Input transform must be either:\n'
                            + '\tvtk.vtkMatrix4x4\n'
                            + '\tvtk.vtkTransform\n'
                            + '\t4x4 np.ndarray\n')

        x = (self.points*t[0, :3]).sum(1) + t[0, -1]
        y = (self.points*t[1, :3]).sum(1) + t[1, -1]
        z = (self.points*t[2, :3]).sum(1) + t[2, -1]

        # overwrite points
        self.points[:, 0] = x
        self.points[:, 1] = y
        self.points[:, 2] = z
811183
def dumpJSON(self):
        
        numexp = self.number.get()
        expTime, _, _, _, _ = self.timing()
        if numexp == 0:
            numexp = -1

        data = dict(
            numexp=self.number.value(),
            app=self.app.value(),
            led_flsh=self.led(),
            dummy_out=self.dummy(),
            fast_clks=self.fastClk(),
            readout=self.readSpeed(),
            dwell=self.expose.value(),
            exptime=expTime,
            oscan=self.oscan(),
            oscany=self.oscany(),
            xbin=self.wframe.xbin.value(),
            ybin=self.wframe.ybin.value(),
            multipliers=self.nmult.getall(),
            clear=self.clear()
        )

        # only allow nodding in clear mode, even if GUI has got confused
        if data['clear'] and self.nodPattern:
            data['nodpattern'] = self.nodPattern

        # no mixing clear and multipliers, no matter what GUI says
        if data['clear']:
            data['multipliers'] = [1 for i in self.nmult.getall()]

        # add window mode
        if not self.isFF():
            if self.isDrift():
                # no clear, multipliers or oscan in drift
                for setting in ('clear', 'oscan', 'oscany'):
                    data[setting] = 0
                data['multipliers'] = [1 for i in self.nmult.getall()]

                for iw, (xsl, xsr, ys, nx, ny) in enumerate(self.wframe):
                    data['x{}start_left'.format(iw+1)] = xsl
                    data['x{}start_right'.format(iw+1)] = xsr
                    data['y{}start'.format(iw+1)] = ys
                    data['y{}size'.format(iw+1)] = ny
                    data['x{}size'.format(iw+1)] = nx
            else:
                # no oscany in window mode
                data['oscany'] = 0

                for iw, (xsll, xsul, xslr, xsur, ys, nx, ny) in enumerate(self.wframe):
                    data['x{}start_upperleft'.format(iw+1)] = xsul
                    data['x{}start_lowerleft'.format(iw+1)] = xsll
                    data['x{}start_upperright'.format(iw+1)] = xsur
                    data['x{}start_lowerright'.format(iw+1)] = xslr
                    data['y{}start'.format(iw+1)] = ys
                    data['x{}size'.format(iw+1)] = nx
                    data['y{}size'.format(iw+1)] = ny
        return data
1186549
def vector_poly_data(orig, vec):
    

    # shape, dimention checking
    if not isinstance(orig, np.ndarray):
        orig = np.asarray(orig)

    if not isinstance(vec, np.ndarray):
        vec = np.asarray(vec)

    if orig.ndim != 2:
        orig = orig.reshape((-1, 3))
    elif orig.shape[1] != 3:
        raise Exception('orig array must be 3D')

    if vec.ndim != 2:
        vec = vec.reshape((-1, 3))
    elif vec.shape[1] != 3:
        raise Exception('vec array must be 3D')

    # Create vtk points and cells objects
    vpts = vtk.vtkPoints()
    vpts.SetData(numpy_to_vtk(np.ascontiguousarray(orig), deep=True))

    npts = orig.shape[0]
    cells = np.hstack((np.ones((npts, 1), 'int'),
                       np.arange(npts).reshape((-1, 1))))

    if cells.dtype != ctypes.c_int64 or cells.flags.c_contiguous:
        cells = np.ascontiguousarray(cells, ctypes.c_int64)
    cells = np.reshape(cells, (2*npts))
    vcells = vtk.vtkCellArray()
    vcells.SetCells(npts, numpy_to_vtkIdTypeArray(cells, deep=True))

    # Create vtkPolyData object
    pdata = vtk.vtkPolyData()
    pdata.SetPoints(vpts)
    pdata.SetVerts(vcells)

    # Add vectors to polydata
    name = 'vectors'
    vtkfloat = numpy_to_vtk(np.ascontiguousarray(vec), deep=True)
    vtkfloat.SetName(name)
    pdata.GetPointData().AddArray(vtkfloat)
    pdata.GetPointData().SetActiveVectors(name)

    # Add magnitude of vectors to polydata
    name = 'mag'
    scalars = (vec * vec).sum(1)**0.5
    vtkfloat = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True)
    vtkfloat.SetName(name)
    pdata.GetPointData().AddArray(vtkfloat)
    pdata.GetPointData().SetActiveScalars(name)

    return vtki.PolyData(pdata)
579391
def dumpb(obj, container_count=False, sort_keys=False, no_float32=True, default=None):
    """"""
    with BytesIO() as fp:
        dump(obj, fp, container_count=container_count, sort_keys=sort_keys, no_float32=no_float32, default=default)
        return fp.getvalue()
482606
def _dump(f, obj, flip_faces=False, ungroup=False, comments=None, split_normals=False, write_mtl=True): # pylint: disable=redefined-outer-name
    '''
    

    '''
    import os
    import numpy as np
    from baiji import s3

    ff = -1 if flip_faces else 1
    def write_face_to_obj_file(obj, faces, face_index, obj_file):
        vertex_indices = faces[face_index][::ff] + 1

        write_normals = obj.fn is not None or (obj.vn is not None and obj.vn.shape == obj.v.shape)
        write_texture = obj.ft is not None and obj.vt is not None

        if write_normals and obj.fn is not None:
            normal_indices = obj.fn[face_index][::ff] + 1
            assert len(normal_indices) == len(vertex_indices)
        elif write_normals: # unspecified fn but per-vertex normals, assume ordering is same as for v
            normal_indices = faces[face_index][::ff] + 1

        if write_texture:
            texture_indices = obj.ft[face_index][::ff] + 1
            assert len(texture_indices) == len(vertex_indices)

        # Valid obj face lines are: v, v/vt, v//vn, v/vt/vn
        if write_normals and write_texture:
            pattern = '%d/%d/%d'
            value = tuple(np.array([vertex_indices, texture_indices, normal_indices]).T.flatten())
        elif write_normals:
            pattern = '%d//%d'
            value = tuple(np.array([vertex_indices, normal_indices]).T.flatten())
        elif write_texture:
            pattern = '%d/%d'
            value = tuple(np.array([vertex_indices, texture_indices]).T.flatten())
        else:
            pattern = '%d'
            value = tuple(vertex_indices)
        obj_file.write(('f ' + ' '.join([pattern]*len(vertex_indices)) + '\n') % value)

    if comments != None:
        if isinstance(comments, basestring):
            comments = [comments]
        for comment in comments:
            for line in comment.split("\n"):
                f.write("# %s\n" % line)

    if write_mtl and hasattr(obj, 'texture_filepath') and obj.texture_filepath is not None:
        save_to = s3.path.dirname(f.name)
        mtl_name = os.path.splitext(s3.path.basename(f.name))[0]
        mtl_filename = mtl_name + '.mtl'
        f.write('mtllib %s\n' % mtl_filename)
        f.write('usemtl %s\n' % mtl_name)
        texture_filename = mtl_name + os.path.splitext(obj.texture_filepath)[1]
        if not s3.exists(s3.path.join(save_to, texture_filename)):
            s3.cp(obj.texture_filepath, s3.path.join(save_to, texture_filename))
        obj.write_mtl(s3.path.join(save_to, mtl_filename), mtl_name, texture_filename)

    if obj.vc is not None:
        for r, c in zip(obj.v, obj.vc):
            f.write('v %f %f %f %f %f %f\n' % (r[0], r[1], r[2], c[0], c[1], c[2]))
    elif obj.v is not None:
        for r in obj.v:
            f.write('v %f %f %f\n' % (r[0], r[1], r[2]))

    if obj.vn is not None:
        if split_normals:
            for vn_idx in obj.fn:
                r = obj.vn[vn_idx[0]]
                f.write('vn %f %f %f\n' % (r[0], r[1], r[2]))
                r = obj.vn[vn_idx[1]]
                f.write('vn %f %f %f\n' % (r[0], r[1], r[2]))
                r = obj.vn[vn_idx[2]]
                f.write('vn %f %f %f\n' % (r[0], r[1], r[2]))
        else:
            for r in obj.vn:
                f.write('vn %f %f %f\n' % (r[0], r[1], r[2]))

    if obj.ft is not None and obj.vt is not None:
        for r in obj.vt:
            if len(r) == 3:
                f.write('vt %f %f %f\n' % (r[0], r[1], r[2]))
            else:
                f.write('vt %f %f\n' % (r[0], r[1]))
    if obj.f4 is not None:
        faces = obj.f4
    elif obj.f is not None:
        faces = obj.f
    else:
        faces = None
    if obj.segm is not None and not ungroup:
        if faces is not None:
            # An array of strings.
            group_names = np.array(obj.segm.keys())

            # A 2d array of booleans indicating which face is in which group.
            group_mask = np.zeros((len(group_names), len(faces)), dtype=bool)
            for i, segm_faces in enumerate(obj.segm.itervalues()):
                group_mask[i][segm_faces] = True

            # In an OBJ file, "g" changes the current state. This is a slice of
            # group_mask that represents the current state.
            current_group_mask = np.zeros((len(group_names),), dtype=bool)

            for face_index in range(len(faces)):
                # If the group has changed from the previous face, write the
                # group entry.
                this_group_mask = group_mask[:, face_index]
                if any(current_group_mask != this_group_mask):
                    current_group_mask = this_group_mask
                    f.write('g %s\n' % ' '.join(group_names[current_group_mask]))

                write_face_to_obj_file(obj, faces, face_index, f)
    else:
        if faces is not None:
            for face_index in range(len(faces)):
                write_face_to_obj_file(obj, faces, face_index, f)
1248095
def _dbg_dump_virtual_outputs(imgObjList):
    
    global _fidx
    tag = 'virtual'
    log.info((tag+'  ')*7)
    for iii in imgObjList:
        log.info('-'*80)
        log.info(tag+'  orig nm: '+iii._original_file_name)
        log.info(tag+'  names.data: '+str(iii.outputNames["data"]))
        log.info(tag+'  names.orig: '+str(iii.outputNames["origFilename"]))
        log.info(tag+'  id: '+str(id(iii)))
        log.info(tag+'  in.mem: '+str(iii.inmemory))
        log.info(tag+'  vo items...')
        for vok in sorted(iii.virtualOutputs.keys()):
            FITSOBJ = iii.virtualOutputs[vok]
            log.info(tag+': '+str(vok)+' = '+str(FITSOBJ))
            if vok.endswith('.fits'):
                if not hasattr(FITSOBJ, 'data'):
                    FITSOBJ = FITSOBJ[0] # list of PrimaryHDU ?
                if not hasattr(FITSOBJ, 'data'):
                    FITSOBJ = FITSOBJ[0] # was list of HDUList ?
                dbgname = 'DEBUG_%02d_'%(_fidx,)
                dbgname+=os.path.basename(vok)
                _fidx+=1
                FITSOBJ.writeto(dbgname)
                log.info(tag+'  wrote: '+dbgname)
                log.info('\n'+vok)
                if hasattr(FITSOBJ, 'data'):
                    log.info(str(FITSOBJ._summary()))
                    log.info('min and max are: '+str( (FITSOBJ.data.min(),
                                                       FITSOBJ.data.max()) ))
                    log.info('avg and sum are: '+str( (FITSOBJ.data.mean(),
                                                       FITSOBJ.data.sum()) ))
#                    log.info(str(FITSOBJ.data)[:75])
                else:
                    log.info(vok+' has no .data attr')
                    log.info(str(type(FITSOBJ)))
                log.info(vok+'\n')
    log.info('-'*80)
1253527
def dump(obj, fp, **kwargs):
    """"""
    kwargs['default'] = serialize
    return json.dump(obj, fp, **kwargs)
845682
function vertexKeyGenerator( v ){
		//this will hold the ids consistently between vertex and vec3ds
		return "[ x: "+format(v.x)+ ", y: "+format(v.y)+ ", z: "+format(v.z)+"]";
	}
1008981
def normalLines(actor, ratio=1, c=(0.6, 0.6, 0.6), alpha=0.8):
    
    maskPts = vtk.vtkMaskPoints()
    maskPts.SetOnRatio(ratio)
    maskPts.RandomModeOff()
    actor = actor.computeNormals()
    src = actor.polydata()
    maskPts.SetInputData(src)
    arrow = vtk.vtkLineSource()
    arrow.SetPoint1(0, 0, 0)
    arrow.SetPoint2(0.75, 0, 0)
    glyph = vtk.vtkGlyph3D()
    glyph.SetSourceConnection(arrow.GetOutputPort())
    glyph.SetInputConnection(maskPts.GetOutputPort())
    glyph.SetVectorModeToUseNormal()
    b = src.GetBounds()
    sc = max([b[1] - b[0], b[3] - b[2], b[5] - b[4]]) / 20.0
    glyph.SetScaleFactor(sc)
    glyph.OrientOn()
    glyph.Update()
    glyphActor = Actor(glyph.GetOutput(), c=vc.getColor(c), alpha=alpha)
    glyphActor.mapper.SetScalarModeToUsePointFieldData()
    glyphActor.PickableOff()
    prop = vtk.vtkProperty()
    prop.DeepCopy(actor.GetProperty())
    glyphActor.SetProperty(prop)
    return glyphActor