Пример #1
0
    def save(self, filename, binary=True):
        """Write a ``MultiBlock`` dataset to disk.

        Written file may be an ASCII or binary vtm file.

        Parameters
        ----------
        filename : str
            Filename of mesh to be written.  File type is inferred from
            the extension of the filename unless overridden with
            ftype.  Can be one of the following types (.vtm or .vtmb)

        binary : bool, optional
            Writes the file as binary when True and ASCII when False.

        Notes
        -----
        Binary files write much faster than ASCII and have a smaller
        file size.

        """
        filename = os.path.abspath(os.path.expanduser(filename))
        ext = pyvista.get_ext(filename)
        if ext in ['.vtm', '.vtmb']:
            writer = vtk.vtkXMLMultiBlockDataWriter()
        else:
            raise Exception('File extension must be either "vtm" or "vtmb"')

        writer.SetFileName(filename)
        writer.SetInputDataObject(self)
        if binary:
            writer.SetDataModeToBinary()
        else:
            writer.SetDataModeToAscii()
        writer.Write()
        return
Пример #2
0
def write(objct, fileoutput, binary=True):
    """
    Write 3D object to file. (same as `save()`).

    Possile extensions are:
        - vtk, vti, npy, ply, obj, stl, byu, vtp, vti, mhd, xyz, tif, png, bmp.
    """
    obj = objct
    if isinstance(obj, Actor): # picks transformation
        obj = objct.polydata(True)
    elif isinstance(obj, (vtk.vtkActor, vtk.vtkVolume)):
        obj = objct.GetMapper().GetInput()
    elif isinstance(obj, (vtk.vtkPolyData, vtk.vtkImageData)):
        obj = objct

    fr = fileoutput.lower()
    if   ".vtk" in fr:
        writer = vtk.vtkPolyDataWriter()
    elif ".ply" in fr:
        writer = vtk.vtkPLYWriter()
        pscal = obj.GetPointData().GetScalars()
        if not pscal:
            pscal = obj.GetCellData().GetScalars()
        if pscal and pscal.GetName():
            writer.SetArrayName(pscal.GetName())
            #writer.SetColorMode(0)
        lut = objct.GetMapper().GetLookupTable()
        if lut:
            writer.SetLookupTable(lut)
    elif ".stl" in fr:
        writer = vtk.vtkSTLWriter()
    elif ".obj" in fr:
        writer = vtk.vtkOBJWriter()
    elif ".vtp" in fr:
        writer = vtk.vtkXMLPolyDataWriter()
    elif ".vtm" in fr:
        g = vtk.vtkMultiBlockDataGroupFilter()
        for ob in objct:
            g.AddInputData(ob)
        g.Update()
        mb = g.GetOutputDataObject(0)
        wri = vtk.vtkXMLMultiBlockDataWriter()
        wri.SetInputData(mb)
        wri.SetFileName(fileoutput)
        wri.Write()
        return mb
    elif ".xyz" in fr:
        writer = vtk.vtkSimplePointsWriter()
    elif ".facet" in fr:
        writer = vtk.vtkFacetWriter()
    elif ".tif" in fr:
        writer = vtk.vtkTIFFWriter()
        writer.SetFileDimensionality(len(obj.GetDimensions()))
    elif ".vti" in fr:
        writer = vtk.vtkXMLImageDataWriter()
    elif ".mhd" in fr:
        writer = vtk.vtkMetaImageWriter()
    elif ".nii" in fr:
        writer = vtk.vtkNIFTIImageWriter()
    elif ".png" in fr:
        writer = vtk.vtkPNGWriter()
    elif ".jpg" in fr:
        writer = vtk.vtkJPEGWriter()
    elif ".bmp" in fr:
        writer = vtk.vtkBMPWriter()
    elif ".npy" in fr:
        if utils.isSequence(objct):
            objslist = objct
        else:
            objslist = [objct]
        dicts2save = []
        for obj in objslist:
            dicts2save.append( _np_dump(obj) )
        np.save(fileoutput, dicts2save)
        return dicts2save

    elif ".xml" in fr:  # write tetrahedral dolfin xml
        vertices = objct.coordinates().astype(str)
        faces = np.array(objct.faces()).astype(str)
        ncoords = vertices.shape[0]
        outF = open(fileoutput, "w")
        outF.write('<?xml version="1.0" encoding="UTF-8"?>\n')
        outF.write('<dolfin xmlns:dolfin="http://www.fenicsproject.org">\n')

        if len(faces[0]) == 4:# write tetrahedral mesh
            ntets = faces.shape[0]
            outF.write('  <mesh celltype="tetrahedron" dim="3">\n')
            outF.write('    <vertices size="' + str(ncoords) + '">\n')
            for i in range(ncoords):
                x, y, z = vertices[i]
                outF.write('      <vertex index="'+str(i)+'" x="'+x+'" y="'+y+'" z="'+z+'"/>\n')
            outF.write('    </vertices>\n')
            outF.write('    <cells size="' + str(ntets) + '">\n')
            for i in range(ntets):
                v0, v1, v2, v3 = faces[i]
                outF.write('     <tetrahedron index="'+str(i)
                           + '" v0="'+v0+'" v1="'+v1+'" v2="'+v2+'" v3="'+v3+'"/>\n')

        elif len(faces[0]) == 3:# write triangle mesh
            ntri = faces.shape[0]
            outF.write('  <mesh celltype="triangle" dim="2">\n')
            outF.write('    <vertices size="' + str(ncoords) + '">\n')
            for i in range(ncoords):
                x, y, dummy_z = vertices[i]
                outF.write('      <vertex index="'+str(i)+'" x="'+x+'" y="'+y+'"/>\n')
            outF.write('    </vertices>\n')
            outF.write('    <cells size="' + str(ntri) + '">\n')
            for i in range(ntri):
                v0, v1, v2 = faces[i]
                outF.write('     <triangle index="'+str(i)+'" v0="'+v0+'" v1="'+v1+'" v2="'+v2+'"/>\n')

        outF.write('    </cells>\n')
        outF.write("  </mesh>\n")
        outF.write("</dolfin>\n")
        outF.close()
        return objct

    else:
        colors.printc("~noentry Unknown format", fileoutput, "file not saved.", c="r")
        return objct

    try:
        if hasattr(writer, 'SetFileTypeToBinary'):
            if binary:
                writer.SetFileTypeToBinary()
            else:
                writer.SetFileTypeToASCII()
        writer.SetInputData(obj)
        writer.SetFileName(fileoutput)
        writer.Write()
        colors.printc("~save Saved file: " + fileoutput, c="g")
    except Exception as e:
        colors.printc("~noentry Error saving: " + fileoutput, "\n", e, c="r")
    return objct
Пример #3
0
  def testRead(self):
    ents = Read(self.filename)
    self.model = smtk.model.Model(ents[0])

    #Verify that the model is marked as discrete
    self.assertEqual(
        self.model.geometryStyle(), smtk.model.DISCRETE,
        'Expected discrete model, got {gs}'.format(gs=self.model.geometryStyle()))

    #Verify that the file contains the proper number of groups.
    subgroups = self.model.groups()
    numGroups = len(subgroups)
    self.assertEqual(numGroups, 3, 'Expected 3 groups, found %d' % numGroups)

    numSubGroupsExpected = [1, 7, 3]
    allgroups = []
    for i in range(len(numSubGroupsExpected)):
        numSubGroups = len(subgroups[i].members())
        self.assertEqual(numSubGroupsExpected[i], numSubGroups,
            'Expected {e} groups, found {a}'.format(e=numSubGroupsExpected[i], a=numSubGroups))
        allgroups += subgroups[i].members()

    #Verify that the group names match those from the Exodus file.
    nameset = {
        'Unnamed block ID: 1 Type: HEX8': '#5a5255',
        'Unnamed set ID: 1':              '#ae5a41',
        'Unnamed set ID: 2':              '#559e83',
        'Unnamed set ID: 3':              '#c3cb71',
        'Unnamed set ID: 4':              '#1b85b8',
        'Unnamed set ID: 5':              '#cb2c31',
        'Unnamed set ID: 6':              '#8b1ec4',
        'Unnamed set ID: 7':              '#ff6700'
    }
    self.assertTrue(all([x.name() in nameset for x in allgroups]),
        'Not all group names recognized.')

    # Verify that no groups which are not in the list above are present.
    groupnames = [x.name() for x in allgroups]
    self.assertTrue(all([x in groupnames for x in nameset]),
        'Some expected group names not present.')

    # Count the number of each *type* of group (node, face, volume)
    #print '\n'.join([str((x.name(), x.flagSummary())) for x in allgroups])
    grouptypes = [x.flagSummary() for x in allgroups]
    gtc = {x:grouptypes.count(x) for x in grouptypes}
    expectedgrouptypecounts = {
      'boundary group (0-d entities)': 3,
      'boundary group (0,1,2-d entities)': 7,
      'domain group (3-d entities)': 1
      }
    for entry in gtc.items():
      print '%40s: %d' % entry
    self.assertEqual(gtc, expectedgrouptypecounts,
        'At least one group was of the wrong type.')

    if self.haveVTK() and self.haveVTKExtension():

        # Render groups with colors:
        for grp in allgroups:
            color = self.hex2rgb(nameset[grp.name()])
            SetEntityProperty(grp, 'color', as_float=color)
            # The element block should not be shown as it is coincident with some
            # of the side sets and throws off baseline images. Remove its tessellation.
            if grp.name() ==  'Unnamed block ID: 1 Type: HEX8':
                grp.setTessellation(smtk.model.Tessellation())

        self.startRenderTest()
        mbs, filt, mapper, actor = self.addModelToScene(self.model)

        self.renderer.SetBackground(1,1,1)
        cam = self.renderer.GetActiveCamera()
        cam.SetFocalPoint(0., 0., 0.)
        cam.SetPosition(19,17,-43)
        cam.SetViewUp(-0.891963, -0.122107, -0.435306)
        self.renderer.ResetCamera()
        self.renderWindow.Render()
        import vtk
        #wri = vtk.vtkCompositeDataWriter()
        #wri.SetInputData(mbs.GetOutputDataObject(0))
        #wri.SetFileName('/tmp/foofar.vtk')
        #wri.Write()
        ## wri = vtk.vtkXMLDataSetWriter()
        wri = vtk.vtkXMLMultiBlockDataWriter()
        wri.SetDataModeToAscii()
        wri.SetInputData(mbs.GetOutputDataObject(0))
        wri.SetFileName('/tmp/foofar.vtm')
        wri.Write()
        try:
          self.assertImageMatch(['baselines', 'exodus', 'disk_out_ref.png'])
        finally:
          self.interact()

    else:
        self.assertFalse(
            self.haveVTKExtension(),
            'Could not import vtk. Python path is {pp}'.format(pp=sys.path))
Пример #4
0
def write(objct, fileoutput, binary=True):
    """
    Write 3D object to file. (same as `save()`).

    Possile extensions are:
        - vtk, vti, npy, ply, obj, stl, byu, vtp, vti, mhd, xyz, tif, png, bmp.
    """
    obj = objct
    if isinstance(obj, Mesh): # picks transformation
        obj = objct.polydata(True)
    elif isinstance(obj, (vtk.vtkActor, vtk.vtkVolume)):
        obj = objct.GetMapper().GetInput()
    elif isinstance(obj, (vtk.vtkPolyData, vtk.vtkImageData)):
        obj = objct

    fr = fileoutput.lower()
    if   fr.endswith(".vtk"):
        writer = vtk.vtkPolyDataWriter()
    elif fr.endswith(".ply"):
        writer = vtk.vtkPLYWriter()
        pscal = obj.GetPointData().GetScalars()
        if not pscal:
            pscal = obj.GetCellData().GetScalars()
        if pscal and pscal.GetName():
            writer.SetArrayName(pscal.GetName())
            #writer.SetColorMode(0)
        lut = objct.GetMapper().GetLookupTable()
        if lut:
            writer.SetLookupTable(lut)
    elif fr.endswith(".stl"):
        writer = vtk.vtkSTLWriter()
    elif fr.endswith(".vtp"):
        writer = vtk.vtkXMLPolyDataWriter()
    elif fr.endswith(".vtm"):
        g = vtk.vtkMultiBlockDataGroupFilter()
        for ob in objct:
            if isinstance(ob, Mesh): # picks transformation
                ob = ob.polydata(True)
            elif isinstance(ob, (vtk.vtkActor, vtk.vtkVolume)):
                ob = ob.GetMapper().GetInput()
            g.AddInputData(ob)
        g.Update()
        mb = g.GetOutputDataObject(0)
        wri = vtk.vtkXMLMultiBlockDataWriter()
        wri.SetInputData(mb)
        wri.SetFileName(fileoutput)
        wri.Write()
        return mb
    elif fr.endswith(".xyz"):
        writer = vtk.vtkSimplePointsWriter()
    elif fr.endswith(".facet"):
        writer = vtk.vtkFacetWriter()
    elif fr.endswith(".tif"):
        writer = vtk.vtkTIFFWriter()
        writer.SetFileDimensionality(len(obj.GetDimensions()))
    elif fr.endswith(".vti"):
        writer = vtk.vtkXMLImageDataWriter()
    elif fr.endswith(".mhd"):
        writer = vtk.vtkMetaImageWriter()
    elif fr.endswith(".nii"):
        writer = vtk.vtkNIFTIImageWriter()
    elif fr.endswith(".png"):
        writer = vtk.vtkPNGWriter()
    elif fr.endswith(".jpg"):
        writer = vtk.vtkJPEGWriter()
    elif fr.endswith(".bmp"):
        writer = vtk.vtkBMPWriter()
    elif fr.endswith(".npy"):
        if utils.isSequence(objct):
            objslist = objct
        else:
            objslist = [objct]
        dicts2save = []
        for obj in objslist:
            dicts2save.append( _np_dump(obj) )
        np.save(fileoutput, dicts2save)
        return dicts2save

    elif fr.endswith(".obj"):
        outF = open(fileoutput, "w")
        outF.write('# OBJ file format with ext .obj\n')
        outF.write('# File Created by vtkplotter\n')
        cobjct = objct.clone().clean()

        for p in cobjct.points():
            outF.write('v '+ str(p[0]) +" "+ str(p[1])+" "+ str(p[2])+'\n')

        for vn in cobjct.normals(cells=False):
            outF.write('vn '+str(vn[0])+" "+str(vn[1])+" "+str(vn[2])+'\n')

        #pdata = cobjct.polydata().GetPointData().GetScalars()
        #if pdata:
        #    ndata = vtk_to_numpy(pdata)
        #    for vd in ndata:
        #        outF.write('vp '+ str(vd) +'\n')

        #ptxt = cobjct.polydata().GetPointData().GetTCoords() # not working
        #if ptxt:
        #    ntxt = vtk_to_numpy(ptxt)
        #    print(len(cobjct.faces()), cobjct.points().shape, ntxt.shape)
        #    for vt in ntxt:
        #        outF.write('vt '+ str(vt[0]) +" "+ str(vt[1])+ ' 0\n')

        for f in cobjct.faces():
            fs = ''
            for fi in f:
                fs += " "+str(fi+1)
            outF.write('f' + fs + '\n')

        #ldata = cobjct.polydata().GetLines().GetData()
        #print(cobjct.polydata().GetLines())
        #if ldata:
        #    ndata = vtk_to_numpy(ldata)
        #    print(ndata)
        #    for l in ndata:
        #        ls = ''
        #        for li in l:
        #            ls += str(li+1)+" "
        #        outF.write('l '+ ls + '\n')

        outF.close()
        return objct

    elif fr.endswith(".xml"):  # write tetrahedral dolfin xml
        vertices = objct.points().astype(str)
        faces = np.array(objct.faces()).astype(str)
        ncoords = vertices.shape[0]
        outF = open(fileoutput, "w")
        outF.write('<?xml version="1.0" encoding="UTF-8"?>\n')
        outF.write('<dolfin xmlns:dolfin="http://www.fenicsproject.org">\n')

        if len(faces[0]) == 4:# write tetrahedral mesh
            ntets = faces.shape[0]
            outF.write('  <mesh celltype="tetrahedron" dim="3">\n')
            outF.write('    <vertices size="' + str(ncoords) + '">\n')
            for i in range(ncoords):
                x, y, z = vertices[i]
                outF.write('      <vertex index="'+str(i)+'" x="'+x+'" y="'+y+'" z="'+z+'"/>\n')
            outF.write('    </vertices>\n')
            outF.write('    <cells size="' + str(ntets) + '">\n')
            for i in range(ntets):
                v0, v1, v2, v3 = faces[i]
                outF.write('     <tetrahedron index="'+str(i)
                           + '" v0="'+v0+'" v1="'+v1+'" v2="'+v2+'" v3="'+v3+'"/>\n')

        elif len(faces[0]) == 3:# write triangle mesh
            ntri = faces.shape[0]
            outF.write('  <mesh celltype="triangle" dim="2">\n')
            outF.write('    <vertices size="' + str(ncoords) + '">\n')
            for i in range(ncoords):
                x, y, dummy_z = vertices[i]
                outF.write('      <vertex index="'+str(i)+'" x="'+x+'" y="'+y+'"/>\n')
            outF.write('    </vertices>\n')
            outF.write('    <cells size="' + str(ntri) + '">\n')
            for i in range(ntri):
                v0, v1, v2 = faces[i]
                outF.write('     <triangle index="'+str(i)+'" v0="'+v0+'" v1="'+v1+'" v2="'+v2+'"/>\n')

        outF.write('    </cells>\n')
        outF.write("  </mesh>\n")
        outF.write("</dolfin>\n")
        outF.close()
        return objct

    else:
        colors.printc("~noentry Unknown format", fileoutput, "file not saved.", c="r")
        return objct

    try:
        if hasattr(writer, 'SetFileTypeToBinary'):
            if binary:
                writer.SetFileTypeToBinary()
            else:
                writer.SetFileTypeToASCII()
        writer.SetInputData(obj)
        writer.SetFileName(fileoutput)
        writer.Write()
    except Exception as e:
        colors.printc("~noentry Error saving: " + fileoutput, "\n", e, c="r")
    return objct
Пример #5
0
def write(objct, fileoutput, binary=True):
    """
    Write 3D object to file. (same as `save()`).

    Possile extensions are:
        - vtk, vti, ply, obj, stl, byu, vtp, vti, mhd, xyz, tif, png, bmp.
    """
    obj = objct
    if isinstance(obj, Actor):  # picks transformation
        obj = objct.polydata(True)
    elif isinstance(obj, (vtk.vtkActor, vtk.vtkVolume)):
        obj = objct.GetMapper().GetInput()
    elif isinstance(obj, (vtk.vtkPolyData, vtk.vtkImageData)):
        obj = objct

    fr = fileoutput.lower()
    if ".vtk" in fr:
        w = vtk.vtkPolyDataWriter()
    elif ".ply" in fr:
        w = vtk.vtkPLYWriter()
    elif ".stl" in fr:
        w = vtk.vtkSTLWriter()
    elif ".vtp" in fr:
        w = vtk.vtkXMLPolyDataWriter()
    elif ".vtm" in fr:
        g = vtk.vtkMultiBlockDataGroupFilter()
        for ob in objct:
            g.AddInputData(ob)
        g.Update()
        mb = g.GetOutputDataObject(0)
        wri = vtk.vtkXMLMultiBlockDataWriter()
        wri.SetInputData(mb)
        wri.SetFileName(fileoutput)
        wri.Write()
        return mb
    elif ".xyz" in fr:
        w = vtk.vtkSimplePointsWriter()
    elif ".facet" in fr:
        w = vtk.vtkFacetWriter()
    elif ".tif" in fr:
        w = vtk.vtkTIFFWriter()
        w.SetFileDimensionality(len(obj.GetDimensions()))
    elif ".vti" in fr:
        w = vtk.vtkXMLImageDataWriter()
    elif ".mhd" in fr:
        w = vtk.vtkMetaImageWriter()
    elif ".png" in fr:
        w = vtk.vtkPNGWriter()
    elif ".jpg" in fr:
        w = vtk.vtkJPEGWriter()
    elif ".bmp" in fr:
        w = vtk.vtkBMPWriter()
    elif ".xml" in fr:  # write tetrahedral dolfin xml
        vertices = obj.coordinates()
        faces = obj.cells()
        ncoords = vertices.shape[0]
        ntets = faces.shape[0]
        outF = open(fileoutput, "w")
        outF.write('<?xml version="1.0" encoding="UTF-8"?>\n')
        outF.write('<dolfin xmlns:dolfin="http://www.fenicsproject.org">\n')
        outF.write('  <mesh celltype="tetrahedron" dim="3">\n')
        outF.write('    <vertices size="' + str(ncoords) + '">\n')
        for i in range(ncoords):
            x, y, z = vertices[i]
            outF.write('      <vertex index="' + str(i) + '" x="' + str(x) +
                       '" y="' + str(y) + '" z="' + str(z) + '"/>\n')
        outF.write('    </vertices>\n')
        outF.write('    <cells size="' + str(ntets) + '">\n')
        for i in range(ntets):
            v0, v1, v2, v3 = faces[i]
            outF.write('      <tetrahedron index="' + str(i) + '" v0="' +
                       str(v0) + '" v1="' + str(v1) + '" v2="' + str(v2) +
                       '" v3="' + str(v3) + '"/>\n')
        outF.write('    </cells>\n')
        outF.write("  </mesh>\n")
        outF.write("</dolfin>\n")
        outF.close()
        return objct
    else:
        colors.printc("~noentry Unknown format",
                      fileoutput,
                      "file not saved.",
                      c="r")
        return objct

    try:
        if hasattr(w, 'SetFileTypeToBinary'):
            if binary:
                w.SetFileTypeToBinary()
            else:
                w.SetFileTypeToASCII()
        w.SetInputData(obj)
        w.SetFileName(fileoutput)
        w.Write()
        colors.printc("~save Saved file: " + fileoutput, c="g")
    except Exception as e:
        colors.printc("~noentry Error saving: " + fileoutput, "\n", e, c="r")
    return objct
Пример #6
0
def main(file_, o):
  """Main program"""

  sp = StatePoint(file_)
  sp.read_results()

  validate_options(sp, o)

  if o.list:
    print_available(sp)
    return

  if o.vtk:
    if not o.output[-4:] == ".vtm": o.output += ".vtm"
  else:
    if not o.output[-5:] == ".silo": o.output += ".silo"

  if o.vtk:
    try:
      import vtk
    except:
      print('The vtk python bindings do not appear to be installed properly.\n'
            'On Ubuntu: sudo apt-get install python-vtk\n'
            'See: http://www.vtk.org/')
      return
  else:
    try:
      import silomesh
    except:
      print('The silomesh package does not appear to be installed properly.\n'
            'See: https://github.com/nhorelik/silomesh/')
      return

  if o.vtk:
    blocks = vtk.vtkMultiBlockDataSet()
    blocks.SetNumberOfBlocks(5)
    block_idx = 0
  else:
    silomesh.init_silo(o.output)

  # Tally loop #################################################################
  for tally in sp.tallies:

    # skip non-mesh tallies or non-user-specified tallies
    if o.tallies and not tally.id in o.tallies: continue
    if not 'mesh' in tally.filters: continue

    print("Processing Tally {}...".format(tally.id))

    # extract filter options and mesh parameters for this tally
    filtercombos = get_filter_combos(tally)
    meshparms = get_mesh_parms(sp, tally)
    nx,ny,nz = meshparms[:3]
    ll = meshparms[3:6]
    ur = meshparms[6:9]

    if o.vtk:
      ww = [(u-l)/n for u,l,n in zip(ur,ll,(nx,ny,nz))]
      grid = grid = vtk.vtkImageData()
      grid.SetDimensions(nx+1,ny+1,nz+1)
      grid.SetOrigin(*ll)
      grid.SetSpacing(*ww)
    else:
      silomesh.init_mesh('Tally_{}'.format(tally.id), *meshparms)

    # Score loop ###############################################################
    for sid,score in enumerate(tally.scores):

      # skip non-user-specified scrores for this tally
      if o.scores and tally.id in o.scores and not sid in o.scores[tally.id]:
        continue

      # Filter loop ############################################################
      for filterspec in filtercombos:

        # skip non-user-specified filter bins
        skip = False
        if o.filters and tally.id in o.filters:
          for filter_,bin in filterspec[1:]:
            if filter_ in o.filters[tally.id] and \
               not bin in o.filters[tally.id][filter_]:
              skip = True
              break
        if skip: continue

        # find and sanitize the variable name for this score
        varname = get_sanitized_filterspec_name(tally, score, filterspec)
        if o.vtk:
          vtkdata = vtk.vtkDoubleArray()
          vtkdata.SetName(varname)
          dataforvtk = {}
        else:
          silomesh.init_var(varname)

        lbl = "\t Score {}.{} {}:\t\t{}".format(tally.id, sid+1, score, varname)

        # Mesh fill loop #######################################################
        for x in range(1,nx+1):
          sys.stdout.write(lbl+" {0}%\r".format(int(x/nx*100)))
          sys.stdout.flush()
          for y in range(1,ny+1):
            for z in range(1,nz+1):
              filterspec[0][1] = (x,y,z)
              val = sp.get_value(tally.id-1, filterspec, sid)[o.valerr]
              if o.vtk:
                # vtk cells go z, y, x, so we store it now and enter it later
                i = (z-1)*nx*ny + (y-1)*nx + x-1
                dataforvtk[i] = float(val)
              else:
                silomesh.set_value(float(val), x, y, z)

        # end mesh fill loop
        print()
        if o.vtk:
          for i in range(nx*ny*nz):
            vtkdata.InsertNextValue(dataforvtk[i])
          grid.GetCellData().AddArray(vtkdata)
          del vtkdata

        else:
          silomesh.finalize_var()

      # end filter loop

    # end score loop
    if o.vtk:
      blocks.SetBlock(block_idx, grid)
      block_idx += 1
    else:
      silomesh.finalize_mesh()

  # end tally loop
  if o.vtk:
    writer = vtk.vtkXMLMultiBlockDataWriter()
    writer.SetFileName(o.output)
    writer.SetInput(blocks)
    writer.Write()
  else:
    silomesh.finalize_silo()
Пример #7
0
    def testRead(self):
        ents = Read(self.filename)
        self.model = smtk.model.Model(ents[0])

        #Verify that the model is marked as discrete
        self.assertEqual(
            self.model.geometryStyle(), smtk.model.DISCRETE,
            'Expected discrete model, got {gs}'.format(
                gs=self.model.geometryStyle()))

        #Verify that the file contains the proper number of groups.
        subgroups = self.model.groups()
        numGroups = len(subgroups)
        self.assertEqual(numGroups, 3,
                         'Expected 3 groups, found %d' % numGroups)

        numSubGroupsExpected = [1, 7, 3]
        allgroups = []
        for i in range(len(numSubGroupsExpected)):
            numSubGroups = len(subgroups[i].members())
            self.assertEqual(
                numSubGroupsExpected[i], numSubGroups,
                'Expected {e} groups, found {a}'.format(
                    e=numSubGroupsExpected[i], a=numSubGroups))
            allgroups += subgroups[i].members()

        #Verify that the group names match those from the Exodus file.
        nameset = {
            'Unnamed block ID: 1 Type: HEX8': '#5a5255',
            'Unnamed set ID: 1': '#ae5a41',
            'Unnamed set ID: 2': '#559e83',
            'Unnamed set ID: 3': '#c3cb71',
            'Unnamed set ID: 4': '#1b85b8',
            'Unnamed set ID: 5': '#cb2c31',
            'Unnamed set ID: 6': '#8b1ec4',
            'Unnamed set ID: 7': '#ff6700'
        }
        self.assertTrue(all([x.name() in nameset for x in allgroups]),
                        'Not all group names recognized.')

        # Verify that no groups which are not in the list above are present.
        groupnames = [x.name() for x in allgroups]
        self.assertTrue(all([x in groupnames for x in nameset]),
                        'Some expected group names not present.')

        # Count the number of each *type* of group (node, face, volume)
        #print '\n'.join([str((x.name(), x.flagSummary())) for x in allgroups])
        grouptypes = [x.flagSummary() for x in allgroups]
        gtc = {x: grouptypes.count(x) for x in grouptypes}
        expectedgrouptypecounts = {
            'boundary group (0-d entities)': 3,
            'boundary group (0,1,2-d entities)': 7,
            'domain group (3-d entities)': 1
        }
        for entry in gtc.items():
            print '%40s: %d' % entry
        self.assertEqual(gtc, expectedgrouptypecounts,
                         'At least one group was of the wrong type.')

        if self.haveVTK() and self.haveVTKExtension():

            # Render groups with colors:
            for grp in allgroups:
                color = self.hex2rgb(nameset[grp.name()])
                SetEntityProperty(grp, 'color', as_float=color)
                # The element block should not be shown as it is coincident with some
                # of the side sets and throws off baseline images. Remove its tessellation.
                if grp.name() == 'Unnamed block ID: 1 Type: HEX8':
                    grp.setTessellation(smtk.model.Tessellation())

            self.startRenderTest()
            mbs, filt, mapper, actor = self.addModelToScene(self.model)

            self.renderer.SetBackground(1, 1, 1)
            cam = self.renderer.GetActiveCamera()
            cam.SetFocalPoint(0., 0., 0.)
            cam.SetPosition(19, 17, -43)
            cam.SetViewUp(-0.891963, -0.122107, -0.435306)
            self.renderer.ResetCamera()
            self.renderWindow.Render()
            import vtk
            #wri = vtk.vtkCompositeDataWriter()
            #wri.SetInputData(mbs.GetOutputDataObject(0))
            #wri.SetFileName('/tmp/foofar.vtk')
            #wri.Write()
            ## wri = vtk.vtkXMLDataSetWriter()
            wri = vtk.vtkXMLMultiBlockDataWriter()
            wri.SetDataModeToAscii()
            wri.SetInputData(mbs.GetOutputDataObject(0))
            wri.SetFileName('/tmp/foofar.vtm')
            wri.Write()
            try:
                self.assertImageMatch(
                    ['baselines', 'exodus', 'disk_out_ref.png'])
            finally:
                self.interact()

        else:
            self.assertFalse(
                self.haveVTKExtension(),
                'Could not import vtk. Python path is {pp}'.format(
                    pp=sys.path))
Пример #8
0
def main():

    parser = create_parser()
    args = parser.parse_args()

    config = config_to_dict(args.config)
    try:
        casePath = config["case"]
        seedPatchName = config["patch"]
        nSamples = int(config["nSamples"])
        writePath = config["file"]
    except KeyError:
        print("ERROR: required parameter not specified in config file.")
        raise

    try:
        debug = bool(int(config["debug"]))
    except KeyError:
        debug = False
        pass

    try:
        time = float(config["time"])
    except KeyError:
        time = None
        pass

    try:
        dry = bool(int(config["dry"]))
    except KeyError:
        dry = False
        pass

    try:
        slow = bool(int(config["slow"]))
    except KeyError:
        slow = False
        print("Will use slow averaging")
        pass

    try:
        patchAlgorithm = str(config["patchalg"])
    except KeyError:
        patchAlgorithm = "cut"
        print("Will use plane cuts for averaging patch data")
        pass

    if debug:
        print("The debug switch is on")
        print("")
        print("The case path is "+casePath)
        print("The name of the seed patch is "+seedPatchName)
        print("The number of samples to be taken along z is "+str(nSamples))
        print("The produced filename will be "+writePath)

    # Case reader
    print("Reading")
    reader = read(casePath, time, debug)
    # Writer
    writer = vtk.vtkXMLMultiBlockDataWriter()
    writer.SetFileName(writePath)

    caseData = reader.GetOutput()
    internalBlock = caseData.GetBlock(0)
    bounds = internalBlock.GetBounds()

    patchBlocks = caseData.GetBlock(1)
    seedPatchBlock = patchBlocks.GetBlock(get_block_index(patchBlocks,
                                                          seedPatchName))

    # The polyData for the 2d fields, copied from the seed patch
    internalData = vtk.vtkPolyData()
    internalData.ShallowCopy(seedPatchBlock)
    internalData.BuildLinks()

    print("Sampling and averaging internal field")
    zero_out_arrays(internalData)
    if slow:
        average_internal_field_data(internalBlock, internalData, nSamples, debug, dry)
    else:
        new_average_internal_field_data(internalBlock, internalData, nSamples, debug, dry)

    print("Creating boundary polyData")
    boundaryData = create_boundary_polydata(patchBlocks, internalData, bounds, debug)

    print("Averaging data for patches")
    average_patch_data(caseData, boundaryData, nSamples, bounds, patchAlgorithm, debug)
    add_boundary_names_to_fielddata(internalData, boundaryData)

    print("Marking boundary cells.")
    mark_boundary_cells(internalData, boundaryData, debug)

    print("Assembling multi-block structure")
    multiBlock = assemble_multiblock(internalData, boundaryData)

    print("Writing")
    writer.SetInputData(multiBlock)
    writer.Write()
Пример #9
0
else:
    usage()
    exit(1)


transforms = dict()
transformers = dict()
data_connectors_v = dict()
data_connectors_t = dict()
data_connectors_d = dict()

big_data_source = vtk.vtkMultiBlockDataGroupFilter()
add_compatiblity_methods(big_data_source)

big_data_writer = vtk.vtkXMLMultiBlockDataWriter()
add_compatiblity_methods(big_data_writer)

contactors = dict()
offsets = dict()

vtkmath = vtk.vtkMath()


class Quaternion():

    def __init__(self, *args):
        self._data = vtk.vtkQuaternion[float](*args)

    def __mul__(self, q):
        r = Quaternion()
g.Update()

mb = g.GetOutputDataObject(0)

a = vtk.vtkFloatArray()
a.SetName("foo")
a.SetNumberOfTuples(1)
a.SetValue(0, 10)

mb.GetFieldData().AddArray(a)

file_root = VTK_TEMP_DIR + '/testxml'
file0 = file_root + ".vtm"

wri = vtk.vtkXMLMultiBlockDataWriter()
wri.SetInputData(mb)
wri.SetFileName(file0)
wri.Write()

read = vtk.vtkXMLMultiBlockDataReader()
read.SetFileName(file0)
read.Update()

output = read.GetOutputDataObject(0)
assert(output.GetFieldData().GetArray("foo"))
assert(output.GetFieldData().GetArray("foo").GetValue(0) == 10)

os.remove(file0)
os.remove(file_root + "/testxml_0.vti")
os.rmdir(file_root)
Пример #11
0
def beam_to_vtk(filename, output = 'beam', option_ISO = False, option_NOT_ISO = False, option_primaries = False, option_secondaries = False):

    file = uproot4.open(filename)
    evt = file.get('Event')

    partID_tracks = evt.arrays(['Trajectory.partID'], library='np')['Trajectory.partID']
    s_tracks = evt.arrays(['Trajectory.S'], library='np')['Trajectory.S']
    tracks = evt.arrays(['Trajectory.XYZ'], library='np')['Trajectory.XYZ']

    mb = _vtk.vtkMultiBlockDataSet()
    mb.SetNumberOfBlocks(len(tracks))

    colors = _vtk.vtkUnsignedCharArray()
    colors.SetNumberOfComponents(3)
    colors.SetName("Colors")

    red = [255, 0, 0]
    green = [0, 255, 0]
    blue = [0, 0, 255]

    mbIndex = 0

    for i in range(len(tracks)):

        for j in range(len(tracks[i])):

            run = False

            if option_ISO and j == 0 and s_tracks[i].tolist()[j][-1] > 15.42:
                run = True
            if option_NOT_ISO and j == 0 and s_tracks[i].tolist()[j][-1] < 15.42:
                run = True
            if option_primaries and j == 0:
                run = True
            if option_secondaries and j != 0:
                run = True

            if partID_tracks[i][j] == 2212:
                color = blue
            elif partID_tracks[i][j] == 2112:
                color = green
            else:
                run = False

            if run:
                steps = tracks[i].tolist()[j]

                lines = _vtk.vtkCellArray()
                pts = _vtk.vtkPoints()

                line0 = _vtk.vtkLine()
                line1 = _vtk.vtkLine()

                pts.InsertNextPoint([steps[0].member('fX'), steps[0].member('fY'), steps[0].member('fZ')])
                line0.GetPointIds().SetId(0, 0)

                for k in range(1, len(steps) - 1):

                    if k % 2 == 0:
                        lines.InsertNextCell(line0)
                        colors.InsertNextTuple(color)
                        line0 = _vtk.vtkLine()
                    if k % 2 == 1 and k != 1:
                        lines.InsertNextCell(line1)
                        colors.InsertNextTuple(color)
                        line1 = _vtk.vtkLine()

                    pts.InsertNextPoint([steps[k].member('fX'), steps[k].member('fY'), steps[k].member('fZ')])
                    line0.GetPointIds().SetId(k % 2, k)
                    line1.GetPointIds().SetId((k - 1) % 2, k)

                # Create a polydata to store everything in
                linesPolyData = _vtk.vtkPolyData()

                # Add the points to the dataset
                linesPolyData.SetPoints(pts)

                # Add the lines to the dataset
                linesPolyData.SetLines(lines)

                # Color the lines
                # colors.InsertNextTuple(color)
                linesPolyData.GetCellData().SetScalars(colors)

                mb.SetBlock(mbIndex, linesPolyData)
                mbIndex += 1

        print(f"Progress: {i / len(tracks) * 100}%")

    writer = _vtk.vtkXMLMultiBlockDataWriter()
    writer.SetDataModeToAscii()
    writer.SetInputData(mb)
    print(f"Trying to write file {output}.vtm")
    writer.SetFileName(f"{output}.vtm")
    writer.Write()
Пример #12
0
g.Update()

mb = g.GetOutputDataObject(0)

a = vtk.vtkFloatArray()
a.SetName("foo")
a.SetNumberOfTuples(1)
a.SetValue(0, 10)

mb.GetFieldData().AddArray(a)

file_root = VTK_TEMP_DIR + '/testxml'
file0 = file_root + ".vtm"

wri = vtk.vtkXMLMultiBlockDataWriter()
wri.SetInputData(mb)
wri.SetFileName(file0)
wri.Write()

read = vtk.vtkXMLMultiBlockDataReader()
read.SetFileName(file0)
read.Update()

output = read.GetOutputDataObject(0)
assert (output.GetFieldData().GetArray("foo"))
assert (output.GetFieldData().GetArray("foo").GetValue(0) == 10)

os.remove(file0)
os.remove(file_root + "/testxml_0.vti")
os.rmdir(file_root)