def NumpyCombinePixelValues(self,inputVolumeNode1, inputVolumeNode2):
    """This method gets Numpy array information from the input volumes and combines 
    the pixel information to give an output numpy array. All input volumes must 
    be the same size"""

    # Print to Slicer CLI
    print('Combining input pixels...'),
    start_time = time.time()

    # Get Image Data for Input Volumes
    imdata1 = inputVolumeNode1.GetImageData()
    imdata2 = inputVolumeNode2.GetImageData()

    # Get Dimensions of First Input (all inputs should match)
    x,y,z   = imdata1.GetDimensions()

    # Get scalar data for all inputs
    scalars1 = imdata1.GetPointData().GetScalars()
    scalars2 = imdata2.GetPointData().GetScalars()

    ## Make Numpy Arrays from Scalar Data
    array1 = numpy_support.vtk_to_numpy(scalars1)
    array2 = numpy_support.vtk_to_numpy(scalars2)

    # Combine Arrays (must divide before summing or will add to more than 256 and wrap around values)
    #outputNumpyarray = array1/2+array2/2
    outputNumpyarray = np.around(27*np.true_divide(array1,array2)) # For Normalization

    # Print to Slicer CLI
    end_time = time.time()
    print('done (%0.2f s)') % float(end_time-start_time)

    return outputNumpyarray
def read_data_and_build_snapshot_matrix(x_min,x_max,y_min,y_max,z_min,z_max,snapshot_dir,file_list,\
						num_snapshots,num_points,num_components,var_name, A):
	reader = vtk.vtkUnstructuredGridReader()
	reader.ReadAllScalarsOn()
	reader.ReadAllVectorsOn()
	extract_region = "false"
	if ( (x_min<x_max) and (y_min<y_max) and (z_min<z_max) ):
		extract_region = "true"
		extract = vtk.vtkExtractUnstructuredGrid()
		extract.SetExtent(x_min, x_max, y_min, y_max, z_min, z_max)
		extract.MergingOn()
	u_temp_read = np.array(np.zeros((num_points,3), dtype=np.float64))
	print '\n   Reading data ...'
	for j in range(0,num_snapshots+1):
		print '      Reading file ', file_list[j].strip(), 'file number ', j, ' of ', num_snapshots
		reader.SetFileName(snapshot_dir + file_list[j].strip())
		reader.Update()
		if (extract_region=="true"):
			extract.SetInput(reader.GetOutput())
			extract.Update()
			u_temp_read = VN.vtk_to_numpy(extract.GetOutput().GetPointData().GetVectors(var_name))
		else:
			u_temp_read = VN.vtk_to_numpy(reader.GetOutput().GetPointData().GetVectors(var_name))
		for k in range(0,num_components):
			A[k*num_points:(k+1)*num_points,j] = u_temp_read[:,k]
Beispiel #3
0
def get_normals(polydata):
    #normals = polydata.GetPointData().GetArray("Normals")
    normals = polydata.GetPointData().GetArray("Normals")
    print numpy_support.vtk_to_numpy(normals)
    

    return numpy_support.vtk_to_numpy(normals)
  def execute(self):
    vessel=self._vessel
    array_v =dict();
            
    for ff in ["ChestRegion"]:
      tmp=vessel.GetPointData().GetArray(ff)
      if isinstance(tmp,vtk.vtkDataArray) == False:
        tmp=vessel.GetFieldData().GetArray(ff)
      array_v[ff]=vtk_to_numpy(tmp)

    xyz_arr=vtk_to_numpy(vessel.GetPoints().GetData())
    
    fig=plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.set_aspect('equal')
    X=xyz_arr[:,0]
    Y=xyz_arr[:,1]
    Z=xyz_arr[:,2]
    ax.scatter(X,Y,Z,s=1,c=array_v['ChestRegion'],marker='.',cmap=plt.cm.jet,linewidth=0)
    ax.grid(True)
    plt.xlabel('x')
    plt.ylabel('y')
    # Create cubic bounding box to simulate equal aspect ratio
    max_range = np.array([X.max()-X.min(), Y.max()-Y.min(), Z.max()-Z.min()]).max()
    Xb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][0].flatten() + 0.5*(X.max()+X.min())
    Yb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][1].flatten() + 0.5*(Y.max()+Y.min())
    Zb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][2].flatten() + 0.5*(Z.max()+Z.min())
    # Comment or uncomment following both lines to test the fake bounding box:
    for xb, yb, zb in zip(Xb, Yb, Zb):
      ax.plot([xb], [yb], [zb], 'w')
    ax.view_init(elev=20.,azim=80)
    fig.savefig(self.output_prefix+'_vasculatureQualityControl.png',dpi=180)
def GetRawDICOMData(filenames,fileID):
  print filenames,fileID
  vtkRealDcmReader = vtk.vtkDICOMImageReader()
  vtkRealDcmReader.SetFileName("%s/%s"%(rootdir,filenames[0]) )
  vtkRealDcmReader.Update()
  vtkRealData = vtk.vtkImageCast()
  vtkRealData.SetOutputScalarTypeToFloat()
  vtkRealData.SetInput( vtkRealDcmReader.GetOutput() )
  vtkRealData.Update( )
  real_image = vtkRealData.GetOutput().GetPointData() 
  real_array = vtkNumPy.vtk_to_numpy(real_image.GetArray(0)) 

  vtkImagDcmReader = vtk.vtkDICOMImageReader()
  vtkImagDcmReader.SetFileName("%s/%s"%(rootdir,filenames[1]) )
  vtkImagDcmReader.Update()
  vtkImagData = vtk.vtkImageCast()
  vtkImagData.SetOutputScalarTypeToFloat()
  vtkImagData.SetInput( vtkImagDcmReader.GetOutput() )
  vtkImagData.Update( )
  imag_image = vtkImagData.GetOutput().GetPointData() 
  imag_array = vtkNumPy.vtk_to_numpy(imag_image.GetArray(0)) 

  vtkAppend = vtk.vtkImageAppendComponents()
  vtkAppend.SetInput( 0,vtkRealDcmReader.GetOutput() )
  vtkAppend.SetInput( 1,vtkImagDcmReader.GetOutput() )
  vtkAppend.Update( )

  vtkDcmWriter = vtk.vtkDataSetWriter()
  vtkDcmWriter.SetFileName("rawdata.%04d.vtk" % fileID )
  vtkDcmWriter.SetInput(vtkAppend.GetOutput())
  vtkDcmWriter.Update()

  return (real_array,imag_array)
Beispiel #6
0
def rdmmag(X1,X2):
    X1 = vtk_to_numpy(X1)
    X2 = vtk_to_numpy(X2)
    rdm  = la.norm(X1/la.norm(X1)-X2/la.norm(X2))
    rmag = abs(1.-la.norm(X2)/la.norm(X1))
    print "  RDM = ",rdm, "\t  rMAG = ",rmag
    return rdm, rmag
Beispiel #7
0
def _extractRectGridByBounds(vtrObj,boundObj):
    '''
    Function that extracts cell from a rectilinear grid (vtr) using bounds.

    Should be signifacantly faster the extractBounds method.

    '''
    import numpy as np, SimPEG as simpeg, vtk
    import vtk.util.numpy_support as npsup

    bO = boundObj.GetBounds()
    xC = npsup.vtk_to_numpy(vtrObj.GetXCoordinates())
    yC = npsup.vtk_to_numpy(vtrObj.GetYCoordinates())
    zC = npsup.vtk_to_numpy(vtrObj.GetZCoordinates())
    iLT = np.where(xC <= bO[0])[0]
    iL = 0 if iLT.shape[0] == 0 else iLT[-1]
    iUT = np.where(xC >= bO[1])[0]
    iU = len(xC) if iUT.shape[0] == 0 else iUT[0]
    jLT = np.where(yC <= bO[2])[0]
    jL = 0 if jLT.shape[0] == 0 else jLT[-1]
    jUT = np.where(yC >= bO[3])[0]
    jU = len(yC) if jUT.shape[0] == 0 else jUT[0]
    kLT = np.where(zC <= bO[4])[0]
    kL = 0 if kLT.shape[0] == 0 else kLT[-1]
    kUT = np.where(zC >= bO[5])[0]
    kU = len(zC) if kUT.shape[0] == 0 else kUT[0]
    extRect = vtk.vtkExtractRectilinearGrid()
    extRect.SetInputData(vtrObj)
    extRect.SetVOI((iL,iU,jL,jU,kL,kU))
    extRect.Update()
    return extRect
Beispiel #8
0
    def PlotData(self):

        # remove any measurement line that might exist
        self.removeMeasurementLine(False)

        if self._usebar is False:
            # handle 'pixel' vs 'mm' options:
            self._transform.Identity()
            self._transform.Scale(self._unit_scalings[self._unit], self._unit_scalings[
                                  self._unit], self._unit_scalings[self._unit])
            self._plotData.Update()
            points = numpy_support.vtk_to_numpy(
                self._plotData.GetPoints().GetData())
            points = (points - points[0]).transpose()
            self.xdata = sum(points * points) ** 0.5
            self.ydata = numpy_support.vtk_to_numpy(
                self._plotData.GetPointData().GetScalars()).astype('float32')
        else:
            inc = abs(self.xdata[1] - self.xdata[0])
            self.lower_panel.m_spinCtrlLower.SetIncrement(inc)
            self.lower_panel.m_spinCtrlUpper.SetIncrement(inc)
            self.lower_panel.m_spinCtrlLower.SetMin(self.xdata[0])
            self.lower_panel.m_spinCtrlLower.SetMax(self.xdata[-1])
            self.lower_panel.m_spinCtrlUpper.SetMin(self.xdata[0])
            self.lower_panel.m_spinCtrlUpper.SetMax(self.xdata[-1])

        self.draw_plot()
        self.canvas.draw()
Beispiel #9
0
def vtk_ensure_trilist(polydata):
    try:
        import vtk
        from vtk.util.numpy_support import vtk_to_numpy

        trilist = vtk_to_numpy(polydata.GetPolys().GetData())

        # 5 is the triangle type - if we have another type we need to
        # use a vtkTriangleFilter
        c = vtk.vtkCellTypes()
        polydata.GetCellTypes(c)

        if c.GetNumberOfTypes() != 1 or polydata.GetCellType(0) != 5:
            warnings.warn('Non-triangular mesh connectivity was detected - '
                          'this is currently unsupported and thus the '
                          'connectivity is being coerced into a triangular '
                          'mesh. This may have unintended consequences.')
            t_filter = vtk.vtkTriangleFilter()
            t_filter.SetInputData(polydata)
            t_filter.Update()
            trilist = vtk_to_numpy(t_filter.GetOutput().GetPolys().GetData())

        return trilist.reshape([-1, 4])[:, 1:]
    except Exception as e:
        warnings.warn(str(e))
        return None
    def read_vtk(self, data_dir='./data', file_name='separatrices.vtk'):
        """
        Read the separatrices from a vtk file.

        call signature:

            read_vtk(data_dir='./data', file_name='separatrices.vtk')

        Arguments:

        *data_dir*:
            Origin data directory.

        *file_name*:
            Origin file name.
        """

        reader = vtk.vtkUnstructuredGridReader()
        reader.SetFileName(os.path.join(data_dir, file_name))
        reader.Update()
        output = reader.GetOutput()

        # Read the separatrices.
        points = output.GetPoints()
        cells = output.GetCells()
        self.separatrices = []
        self.connectivity = []
        for separatrix in range(points.GetNumberOfPoints()):
            self.separatrices.append(points.GetPoint(separatrix))
        self.separatrices = np.array(self.separatrices)
        self.connectivity = np.array([VN.vtk_to_numpy(cells.GetData())[1::3],
                                      VN.vtk_to_numpy(cells.GetData())[2::3]])
        self.connectivity = self.connectivity.swapaxes(0, 1)
Beispiel #11
0
def loadVtk(filename):
    if 'vtp' in filename:
        vreader = vtk.vtkXMLPolyDataReader()
    else:
        vreader = vtk.vtkPolyDataReader()

    vreader.SetFileName(filename)
    vreader.Update()
    polydata = vreader.GetOutput()
    polydata.ReleaseDataFlagOn()

    streamlines = []
    verts = vtk_to_numpy(polydata.GetPoints().GetData())
    scalars = {}

    pointdata = polydata.GetPointData()
    for si in range(pointdata.GetNumberOfArrays()):
        sname =  pointdata.GetArrayName(si)
        scalars[sname] = vtk_to_numpy(pointdata.GetArray(si))

    for i in range(polydata.GetNumberOfCells()):
        pids =  polydata.GetCell(i).GetPointIds()
        ids = [ pids.GetId(p) for p in range(pids.GetNumberOfIds())]
        streamlines.append(ids)

    res = {'points':verts, 'values':scalars, 'streamlines':streamlines}
    return res
 def test_pointdata(self):
     self.nrrdArray = ns.vtk_to_numpy(
         self.rnrrd.GetOutput().GetPointData().GetScalars()
     )
     self.itkArray = ns.vtk_to_numpy(
         self.ritk.GetOutput().GetPointData().GetScalars()
     )
     self.assertTrue(numpy.allclose(self.nrrdArray, self.itkArray))
def rdmmag(X1, X2):
    """Rdm and Mag calculation."""
    X1 = vtk_to_numpy(X1)
    X2 = vtk_to_numpy(X2)
    rdm = la.norm(X1 / la.norm(X1) - X2 / la.norm(X2))
    rmag = abs(1. - la.norm(X2) / la.norm(X1))
    print("  RDM = ", rdm, "\t  rMAG = ", rmag)
    return rdm, rmag
Beispiel #14
0
def getDataArray(vtkObj,name,arrType='Cell'):
    """Function that returns the cell/point data array. """
    return npsup.vtk_to_numpy(vtkObj.GetCellData().GetArray(name))
    if arrType == 'Cell':
        return npsup.vtk_to_numpy(vtkObj.GetCellData().GetArray(name))
    elif arrType == 'Point':
        return npsup.vtk_to_numpy(vtkObj.GetPointData().GetArray(name))
    else:
        raise Exception('Not a support arrType')
Beispiel #15
0
def read_paths(fold):
    print fold
    fname = fold+'/pathsq.vtk'
    print fname
    npArray = fold+'/pathsq'    # fname = '/home/florian/MEGAsync/calcul/LCS_tractor/data/paths.vtk'
    if os.path.isfile(npArray + '.npy'):
        print 'loading ', npArray
        t0 = time.time()
        xx = np.load(npArray + '.npy')
        print 'already existing array loaded in', time.time() - t0, 's'
    else:
        reader = vtk.vtkPolyDataReader()
        reader.SetFileName(fname)
        reader.Update()
        data = reader.GetOutput()
        ll = data.GetLines()
        n_pts = ll.GetSize()  # nb of points
        n_lines = ll.GetNumberOfCells()  # nb of lines
        idList = vtk.vtkIdList()
        idList.SetNumberOfIds(n_lines)
        print idList
        idList.SetId(0, 0)
        abscissaArray = vtk.vtkFloatArray()
        traj = []  # list of pos
        vel = []  # list of vel
        vort = []  # list of vort
        k = 0
        for i in xrange(n_lines):
            cell = data.GetCell(i)
            abscissa = 0.0
            previousPoint = None
            if i % np.int(n_lines / 100) == 0:
                print k, '% read'
                k += 1


            llength = cell.GetNumberOfPoints()
            pos = []  # np.empty([llength, 3])  # pos, u, vort
            u = []  # np.empty([llength, 3])  # pos, u, vort
            vorti = []  # np.empty([llength])  # pos, u, vort
            for j in range(llength):
                pointId = cell.GetPointId(j)
                pos.append(data.GetPoint(pointId))
                u.append(vtk_to_numpy(data.GetPointData().GetArray("U"))[pointId])
                vorti.append(vtk_to_numpy(data.GetPointData().GetArray("Vorticity"))[pointId])

            traj.append(pos)
            vel.append(u)
            vort.append(vorti)

        # print traj
        # x = [traj, vel, vort]
        xx = np.array([traj,vel,vort])
        np.save(npArray, xx)
        print 'shit\'s read'
        print 'end of path lines reading'
    return xx
Beispiel #16
0
 def __init__(self, dataDir = 'data', streamFile = 'stream.vtk'):
     """
     Read the initial streamlines.
     
     call signature:
     
       readStream(dataDir = 'data', streamFile = 'stream.vtk')
       
     Keyword arguments:
      *dataDir*:
         Data directory.
         
      *streamFile*:
         Read the initial streamline from this file.
     """
 
     # load the data
     reader = vtk.vtkPolyDataReader()
     reader.SetFileName(dataDir + '/' + streamFile)
     reader.Update()
     output = reader.GetOutput()
     
     # get the fields
     field = output.GetFieldData()
     nArrays = field.GetNumberOfArrays()
     class params: pass
     p = params()
     for i in range(nArrays):            
         arrayName = field.GetArrayName(i)
         if any(arrayName == np.array(['l', 'sl'])):
             setattr(self, arrayName, VN.vtk_to_numpy(field.GetArray(arrayName)))
         elif any(arrayName == np.array(['hMin', 'hMax', 'lMax', 'tol', 'iterMax', 'nt'])):
             setattr(self, arrayName, VN.vtk_to_numpy(field.GetArray(arrayName))[0])
         else:
             # change this if parameters can have more than one entry
             setattr(p, arrayName, VN.vtk_to_numpy(field.GetArray(arrayName))[0])
     setattr(self, 'p', p)
     
     # get the points
     points = output.GetPoints()
     pointsData = points.GetData()
     data = VN.vtk_to_numpy(pointsData)
     #data = np.swapaxes(data, 0, 1)
     print self.nt
     print self.sl
     print data.shape
     tracers = np.zeros([self.nt, np.max(self.sl), 3], dtype = data.dtype)
     sl = 0
     for i in range(self.nt):
         #if (i > 0):
             #sl = self.sl[i-1]
         #else:
             #sl = 0
         print sl, self.sl[i]
         tracers[i,:self.sl[i],:] = data[sl:sl+self.sl[i],:]
         sl += self.sl[i]
     setattr(self, 'tracers', tracers)
Beispiel #17
0
def ply_importer(filepath, asset=None, texture_resolver=None, **kwargs):
    """Allows importing Wavefront (OBJ) files.

    Uses VTK.

    Parameters
    ----------
    asset : `object`, optional
        An optional asset that may help with loading. This is unused for this
        implementation.
    texture_resolver : `callable`, optional
        A callable that recieves the mesh filepath and returns a single
        path to the texture to load.
    \**kwargs : `dict`, optional
        Any other keyword arguments.

    Returns
    -------
    shape : :map:`PointCloud` or subclass
        The correct shape for the given inputs.
    """
    import vtk
    from vtk.util.numpy_support import vtk_to_numpy

    ply_importer = vtk.vtkPLYReader()
    ply_importer.SetFileName(str(filepath))

    ply_importer.Update()

    # Get the output
    polydata = ply_importer.GetOutput()

    # We must have point data!
    points = vtk_to_numpy(polydata.GetPoints().GetData()).astype(np.float)

    trilist = np.require(vtk_ensure_trilist(polydata), requirements=['C'])

    texture = None
    if texture_resolver is not None:
        texture_path = texture_resolver(filepath)
        if texture_path is not None and texture_path.exists():
            texture = mio.import_image(texture_path)

    tcoords = None
    if texture is not None:
        try:
            tcoords = vtk_to_numpy(polydata.GetPointData().GetTCoords())
        except Exception:
            pass

        if isinstance(tcoords, np.ndarray) and tcoords.size == 0:
            tcoords = None

    colour_per_vertex = None
    return _construct_shape_type(points, trilist, tcoords, texture,
                                 colour_per_vertex)
 def feature_extractor(self,in_vtk):
   points = vtk_to_numpy(in_vtk.GetPoints().GetData())
   vec= vtk_to_numpy(in_vtk.GetPointData().GetArray("hevec0"))
   #features =np.concatenate((points, vec[:,0:1]),axis=1)
   features = points
   #features=StandardScaler().fit_transform(features)
   pca = PCA(n_components=4)
   pca.fit(features)
   features_t=pca.transform(features)
   return features_t[:,[0,1]]
    def read_vtk(self, data_dir='./data', file_name='nulls.vtk'):
        """
        Read the null point from a vtk file.

        call signature:

            read_vtk(data_dir='./data', file_name='nulls.vtk')

        Arguments:

        *data_dir*:
            Origin data directory.

        *file_name*:
            Origin file name.
        """

        reader = vtk.vtkUnstructuredGridReader()
        reader.SetFileName(os.path.join(data_dir, file_name))
        reader.Update()
        output = reader.GetOutput()

        # Read the null points.
        points = output.GetPoints()
        self.nulls = []
        for null in range(points.GetNumberOfPoints()):
            self.nulls.append(points.GetPoint(null))
        self.nulls = np.array(self.nulls)

        point_data = output.GetPointData()
        eigen_values_vtk = []
        eigen_values = []
        eigen_vectors_vtk = []
        eigen_vectors = []
        fan_vectors_vtk = []
        fan_vectors = []
        for dim in range(3):
            eigen_values_vtk.append(point_data.GetVectors('eigen_value_{0}'.format(dim)))
            eigen_values.append(VN.vtk_to_numpy(eigen_values_vtk[-1]))
            eigen_vectors_vtk.append(point_data.GetVectors('eigen_vector_{0}'.format(dim)))
            eigen_vectors.append(VN.vtk_to_numpy(eigen_vectors_vtk[-1]))
            if dim < 2:
                fan_vectors_vtk.append(point_data.GetVectors('fan_vector_{0}'.format(dim)))
                fan_vectors.append(VN.vtk_to_numpy(fan_vectors_vtk[-1]))
        sign_trace_vtk = point_data.GetVectors('sign_trace')
        sign_trace = VN.vtk_to_numpy(sign_trace_vtk)
        normals_vtk = point_data.GetVectors('normal')
        normals = VN.vtk_to_numpy(normals_vtk)

        self.eigen_values = np.swapaxes(np.array(eigen_values), 0, 1)
        self.eigen_vectors = np.swapaxes(np.array(eigen_vectors), 0, 1)
        self.fan_vectors = np.swapaxes(np.array(fan_vectors), 0, 1)
        self.sign_trace = np.array(sign_trace)
        self.normals = np.array(normals)
Beispiel #20
0
def get_points_normals_from(polydata):

    nodes_vtk_array = polydata.GetPoints().GetData()
    array = vtk_to_numpy(nodes_vtk_array)

    numberArrays = polydata.GetPointData().GetNumberOfArrays()
    for i in range(numberArrays):
        if polydata.GetPointData().GetArrayName(i) == "Normals":
            array_normals = vtk_to_numpy(polydata.GetPointData().GetScalars("Normals"))
            return array, array_normals
    else:
        raise Exception("No available Normals")
Beispiel #21
0
 def PrepareMesh(self, nclus, subratio, verbose):
     """ Initialize mesh parameters, to include subdividing mesh if necessary"""
     
     # Check if the mesh needs to be subdivided
     if self.mode == 'face':
         n = self.origmesh.GetPolys().GetNumberOfCells()
     else:
         n = self.origmesh.GetPoints().GetNumberOfPoints()
     
     # Required number of points/faces
     nreq = nclus*subratio
     
     if nreq > n:
         
         # Determine the number of subdivisions given that each subdivision generates 4 triangles
         # per single triangle input or two points per triangle
         if self.mode == 'face':
             nsub = int(ceil(log(float(nreq)/n, 4))) # solved given nreq = n*4**nsub
         else:
             nsub = int(ceil(log(float(nreq)/n, 3))) # solved given nreq = n*2**nsub
         
         if verbose:
             print('Subdividing mesh with {:d} subdivision(s)'.format(nsub)); sys.stdout.flush()
         
         # Perform subdivision
         self.mesh = SubdivideMesh(self.origmesh, nsub)
     else:
         self.mesh = self.origmesh
     
     # Extract vertices and faces of mesh
     f = VN.vtk_to_numpy(self.mesh.GetPolys().GetData()).reshape((-1, 4)).astype(np.int32)
     v = VN.vtk_to_numpy(self.mesh.GetPoints().GetData()).astype(np.float)     
     
     # Store faces without padding
     self.fc = f[:, 1:]
     
     
     if self.mode == 'face':
         # Get face areas and centroids
         self.area = GetTriangleArea(v, f)
         self.cent = v.take(self.fc, axis=0).mean(1)
         
     else:
         # Compute the mean of area of the triangles adjcent to a point
         self.area = GetPointWeight(v, f)
         
         # Centers are simply the surface points
         self.cent = v
         
     # Develop face/edge associations or get the points at either edge of unique edges
     self.edgeID = GetEdgeID(self.fc, self.mode)
     self.nclus = nclus
  def extract_particles(self,ids):
    data=vtk.vtkPolyData()
    points=vtk_to_numpy(self._in_vtk.GetPoints().GetData())

    s_points=vtk.vtkPoints()
    cell_arr=vtk.vtkCellArray()
    
    #s_points.SetData(numpy_to_vtk(points[ids,:]))
    #s_points.SetNumberOfPoints(s_points.GetData().GetNumberOfTuples())
    s_p = points[ids,:]
    s_points.SetNumberOfPoints(s_p.shape[0])
    cell_arr.SetNumberOfCells(s_p.shape[0])
    for kk in xrange(s_p.shape[0]):
      s_points.SetPoint(kk,s_p[kk,0],s_p[kk,1],s_p[kk,2])
      cell_arr.InsertNextCell(1)
      cell_arr.InsertCellPoint(kk)
    
    data.SetPoints(s_points)
    data.SetVerts(cell_arr)
    
    #Transfer point data and field data
    for pd,out_pd in zip([self._in_vtk.GetPointData(),self._in_vtk.GetFieldData()],[data.GetPointData(),data.GetFieldData()]):
      for k in xrange(pd.GetNumberOfArrays()):
        arr=vtk_to_numpy(pd.GetArray(pd.GetArrayName(k)))
        if len(arr.shape) == 1:
          s_vtk_arr=numpy_to_vtk(arr[ids],1)
        else:
          s_vtk_arr=numpy_to_vtk(arr[ids,:],1)
        
        s_vtk_arr.SetName(pd.GetArrayName(k))
        out_pd.AddArray(s_vtk_arr)
    
    return data
                      
    #Method to do the extraction using a vtk pipeline (experimental with seg fault)
    def extract_using_vtk(self,ids):
      node=vtk.vtkSelectionNode()
      sel = vtk.vtkSelection()
      node.GetProperties().Set(vtk.vtkSelectionNode.CONTENT_TYPE(),\
                               vtk.vtkSelectionNode.INDICES)
      node.GetProperties().Set(vtk.vtkSelectionNode.FIELD_TYPE(),\
                               vtk.vtkSelectionNode.POINT)
      
      #Create Id Array with point Ids for each cluster
      vtk_ids=numpy_to_vtkIdTypeArray(ids)
      node.SetSelectionList(vtk_ids)
      #sel_filter = vtk.vtkExtractSelectedPolyDataIds()
      sel_filter = vtk.vtkExtractSelection()
      sel_filter.SetInput(0,self._in_vtk)
      sel_filter.SetInput(1,sel)
      sel_filter.Update()
      return sel_filter.GetOutput()
Beispiel #23
0
def compute_nonzeromean(polydata,inarrayname,pointdata=True):

    if polydata.GetNumberOfPoints() > 0 :
        if pointdata:
            array = vtk_to_numpy(polydata.GetPointData().GetArray(inarrayname))
        else:
            array = vtk_to_numpy(polydata.GetCellData().GetArray(inarrayname))

        array_masked = np.ma.array( array, mask = (array <= 0) )
        array_nonan = array_masked[~np.isnan(array_masked)]
        return array_nonan.mean()
    else:
        return 0.
def GetRawDICOMData(filenames,fileID):
  print filenames,fileID
  vtkRealDcmReader = vtk.vtkDICOMImageReader()
  vtkRealDcmReader.SetFileName("%s/%s"%(rootdir,filenames[0]) )
  vtkRealDcmReader.Update()
  vtkRealData = vtk.vtkImageCast()
  vtkRealData.SetOutputScalarTypeToFloat()
  vtkRealData.SetInput( vtkRealDcmReader.GetOutput() )
  vtkRealData.Update( )
  real_image = vtkRealData.GetOutput().GetPointData() 
  real_array = vtkNumPy.vtk_to_numpy(real_image.GetArray(0)) 

  vtkImagDcmReader = vtk.vtkDICOMImageReader()
  vtkImagDcmReader.SetFileName("%s/%s"%(rootdir,filenames[1]) )
  vtkImagDcmReader.Update()
  vtkImagData = vtk.vtkImageCast()
  vtkImagData.SetOutputScalarTypeToFloat()
  vtkImagData.SetInput( vtkImagDcmReader.GetOutput() )
  vtkImagData.Update( )
  imag_image = vtkImagData.GetOutput().GetPointData() 
  imag_array = vtkNumPy.vtk_to_numpy(imag_image.GetArray(0)) 

  vtkAppend = vtk.vtkImageAppendComponents()
  vtkAppend.SetInput( 0,vtkRealDcmReader.GetOutput() )
  vtkAppend.SetInput( 1,vtkImagDcmReader.GetOutput() )
  vtkAppend.Update( )

  # write raw data
  vtkRawData = vtkAppend.GetOutput()
  vtkRawData.SetSpacing( spacing )
  vtkDcmWriter = vtk.vtkDataSetWriter()
  vtkDcmWriter.SetFileTypeToBinary()
  vtkDcmWriter.SetFileName("s%d/rawdata.%04d.vtk" % (dirID,fileID) )
  vtkDcmWriter.SetInput( vtkRawData )
  vtkDcmWriter.Update()

  # write raw phase data
  vtkPhase = vtk.vtkImageMathematics()
  vtkPhase.SetInput1( vtkRealData.GetOutput() )
  vtkPhase.SetInput2( vtkImagData.GetOutput() )
  vtkPhase.SetOperationToATAN2( )
  vtkPhase.Update( )
  vtkPhaseData = vtkPhase.GetOutput()
  vtkPhaseData.SetSpacing( spacing )
  vtkDcmWriter = vtk.vtkDataSetWriter()
  vtkDcmWriter.SetFileTypeToBinary()
  vtkDcmWriter.SetFileName("s%d/phase.%04d.vtk" % (dirID,fileID) )
  vtkDcmWriter.SetInput( vtkPhaseData)
  vtkDcmWriter.Update()

  return (real_array,imag_array)
Beispiel #25
0
    def __init__(self, polyData):
        vertices3D = convert.vtk_to_numpy(polyData.GetPoints().GetData())
        # FiPy needs its coordinates in an array like:
        # [[x0, x1, ..., xn-1],
        #  [y0, y1, ..., yn-1]]
        # VTK gives us:
        # [[x0, y0, z0],
        #  [x1, y1, z1],
        #  ...,
        #  [xn-1, yn-1, zn-1]]
        self.vertices = vertices3D[:,0:2].transpose()

        # VTK gives us a flat array of cells like
        # [nPoints, pId0, pId1, pId2, ... nPoints,... ]
        cells = convert.vtk_to_numpy(polyData.GetPolys().GetData())
        self.nTris = nTris = polyData.GetPolys().GetNumberOfCells()
        cells.shape = (nTris, 4)
        # So now cells[i] contains (3, id0, id1, id2) for triangle i
        
        # FiPy requires a list of the FACES (in 2D the lines) making up each 
        # cell. Make the array the maximum possible size for now.
        self.faces = np.zeros((2, 3*nTris), dtype=np.int)
        
        # Since these have to be unique, construct a sparse lookup matrix 
        # (a dictionary is very sloooooow)
        ############################################################
        # SUPER IMPORTANT- since the default value of the matrix is 
        # zero, we're going to use 1-indexing for these so +1 when 
        # writing and -1 when reading.
        ############################################################
        self.faceCache = lil_matrix((nTris,nTris), dtype=np.int)
        # Track the number of faces added.
        self.nFaces = 0
        
        # A cell is defined by the IDs of its faces
        self.cells = np.zeros((3, nTris), dtype=np.int)
        # Track the number added
        self.nCells = 0
        
        for triPtIds in cells[:,1:]:
            for i in xrange(3):
                self.cells[i, self.nCells] = self._InsertUniqueFace(triPtIds[i],
                                                                    triPtIds[(i+1) % 3])
                continue
            self.nCells += 1
            continue
        
        # Trim the unused face rows
        self.faces = self.faces[:,:self.nFaces]
        return
Beispiel #26
0
def readVTK(reader,fname):
    reader.SetFileName(fname)
    reader.Update()
        
    polydata = reader.GetOutput()
    nodes_vtk_array= polydata.GetPoints().GetData()
    var_vtk_array = polydata.GetCellData().GetArray(0)

    #Get the coordinates of the nodes and their temperatures
    nodes_nummpy_array = numpy_support.vtk_to_numpy(nodes_vtk_array)
    x,y,z= nodes_nummpy_array[:,0] , nodes_nummpy_array[:,1] , nodes_nummpy_array[:,2]

    var_numpy_array = numpy_support.vtk_to_numpy(var_vtk_array)
    return var_numpy_array
	def OnNavR(self, prev_ped_id):
		out_polys = self.areapoly1.GetOutputDataObject(0)
		poly_bounds = VN.vtk_to_numpy(out_polys.GetCellData().GetArray('area'))
		vertex_ids = VN.vtk_to_numpy(out_polys.GetCellData().GetArray('vertex_ids'))
		
		same_scale_ids = N.nonzero(self.ds.Scales==self.ds.Scales[prev_ped_id])[0]
		same_scale_xmins = poly_bounds[self.ds.Scales==self.ds.Scales[prev_ped_id], 0]
		ordered_scale_ids = same_scale_ids[same_scale_xmins.argsort()]
		prev_idx = N.nonzero(ordered_scale_ids==prev_ped_id)[0]
		
		if prev_idx < (ordered_scale_ids.size - 1):
			return ordered_scale_ids[prev_idx + 1]
		else:
			return ordered_scale_ids[prev_idx]
Beispiel #28
0
def readVTRFile(fileName):
    """
        Read VTK Rectilinear (vtr xml file) and return SimPEG Tensor mesh and model

        Input:
        :param vtrFileName, path to the vtr model file to write to

        Output:
        :return SimPEG TensorMesh object
        :return SimPEG model dictionary
        
    """
    # Import
    from vtk import vtkXMLRectilinearGridReader as vtrFileReader
    from vtk.util.numpy_support import vtk_to_numpy

    # Read the file
    vtrReader = vtrFileReader()
    vtrReader.SetFileName(fileName)
    vtrReader.Update()
    vtrGrid = vtrReader.GetOutput()
    # Sort information
    hx = np.abs(np.diff(vtk_to_numpy(vtrGrid.GetXCoordinates())))
    xR = vtk_to_numpy(vtrGrid.GetXCoordinates())[0]
    hy = np.abs(np.diff(vtk_to_numpy(vtrGrid.GetYCoordinates())))
    yR = vtk_to_numpy(vtrGrid.GetYCoordinates())[0]
    zD = np.diff(vtk_to_numpy(vtrGrid.GetZCoordinates()))
    # Check the direction of hz
    if np.all(zD < 0):
        hz = np.abs(zD[::-1])
        zR = vtk_to_numpy(vtrGrid.GetZCoordinates())[-1]
    else:
        hz = np.abs(zD)
        zR = vtk_to_numpy(vtrGrid.GetZCoordinates())[0]
    x0 = np.array([xR,yR,zR])

    # Make the SimPEG object
    from SimPEG import Mesh
    tensMsh = Mesh.TensorMesh([hx,hy,hz],x0)

    # Grap the models
    modelDict = {}
    for i in np.arange(vtrGrid.GetCellData().GetNumberOfArrays()):
        modelName = vtrGrid.GetCellData().GetArrayName(i)
        if np.all(zD < 0):
            modFlip = vtk_to_numpy(vtrGrid.GetCellData().GetArray(i))
            tM = tensMsh.r(modFlip,'CC','CC','M')
            modArr = tensMsh.r(tM[:,:,::-1],'CC','CC','V')
        else:
            modArr = vtk_to_numpy(vtrGrid.GetCellData().GetArray(i))
        modelDict[modelName] = modArr

    # Return the data
    return tensMsh, modelDict
Beispiel #29
0
def vtkPolyData_to_tracts(polydata, return_tractography_object=True):
    r'''
    Reads a VTKPolyData object and outputs a tracts/tracts_data pair

    Parameters
    ----------
    polydata : vtkPolyData
        VTKPolyData Object

    Returns
    -------
    tracts : list of float array N_ix3
        Each element of the list is a tract represented as point array,
        the length of the i-th tract is N_i
    tract_data : dict of <data name>= list of float array of N_ixM
        Each element in the list corresponds to a tract,
        N_i is the length of the i-th tract and M is the
        number of components of that data type.
    '''

    result = {}
    result['lines'] = ns.vtk_to_numpy(polydata.GetLines().GetData())
    result['points'] = ns.vtk_to_numpy(polydata.GetPoints().GetData())
    result['numberOfLines'] = polydata.GetNumberOfLines()

    data = {}
    if polydata.GetPointData().GetScalars():
        data['ActiveScalars'] = polydata.GetPointData().GetScalars().GetName()
    if polydata.GetPointData().GetVectors():
        data['ActiveVectors'] = polydata.GetPointData().GetVectors().GetName()
    if polydata.GetPointData().GetTensors():
        data['ActiveTensors'] = polydata.GetPointData().GetTensors().GetName()

    for i in range(polydata.GetPointData().GetNumberOfArrays()):
        array = polydata.GetPointData().GetArray(i)
        np_array = ns.vtk_to_numpy(array)
        if np_array.ndim == 1:
            np_array = np_array.reshape(len(np_array), 1)
        data[polydata.GetPointData().GetArrayName(i)] = np_array

    result['pointData'] = data

    tracts, data = vtkPolyData_dictionary_to_tracts_and_data(result)
    if return_tractography_object:
        tr = Tractography()
        tr.append(tracts, data)
        return tr
    else:
        return tracts, data
def get_cell_volumes(x_min,x_max,y_min,y_max,z_min,z_max,filename,cell_volume):
	reader = vtk.vtkUnstructuredGridReader()
	reader.ReadAllScalarsOn()
	reader.ReadAllVectorsOn()
	reader.SetFileName(filename)
	reader.Update()
	if ( (x_min<x_max) and (y_min<y_max) and (z_min<z_max) ):
		extract = vtk.vtkExtractUnstructuredGrid()
		extract.SetExtent(x_min, x_max, y_min, y_max, z_min, z_max)
		extract.SetInput(reader.GetOutput())
		extract.MergingOn()
		extract.Update()
		cell_volume = VN.vtk_to_numpy(extract.GetOutput().GetPointData().GetScalars("cell_volume"))
	else:
		cell_volume = VN.vtk_to_numpy(reader.GetOutput().GetPointData().GetScalars("cell_volume"))
Beispiel #31
0
def convert(input, output, force=True, only_points=True):

    # print('Converting', len(input), 'files.')

    file_i = input

    if not os.path.exists(file_i):
        print('ERROR', 'Could not find file:', file_i)
        return

    # print('Converting', file_i)

    input_basename = os.path.basename(file_i)

    if input_basename.endswith('vtp'):

        r = vtk.vtkXMLPolyDataReader()
        r.SetFileName(file_i)
        r.Update()
        polydata = r.GetOutput()

    elif input_basename.endswith('vtk'):

        r = vtk.vtkPolyDataReader()
        r.SetFileName(file_i)
        r.Update()
        polydata = r.GetOutput()

    points = numpy_support.vtk_to_numpy(polydata.GetPoints().GetData())
    lines = numpy_support.vtk_to_numpy(polydata.GetLines().GetData())
    number_of_streamlines = polydata.GetLines().GetNumberOfCells()

    # if (number_of_streamlines == 0):

    #   print('ERROR', 'No streamlines in file:', file_i)
    #   continue

    #
    # convert to streamlines
    #
    streamlines = []
    i = 0
    current_fiber_id = 0
    line_length = 0
    if len(lines) > 0:
        line_length = lines[i]
    line_index = 0

    while (line_index < number_of_streamlines):
        #     print(line_index,'start',i+1,'len',line_length)

        current_line = lines[i + 1 + line_index:i + 1 + line_length +
                             line_index]
        current_points = np.zeros((line_length, 3), dtype=np.float32)

        for p_i, p in enumerate(current_line):
            current_points[p_i] = points[p]

        streamlines.append(current_points)

        i += line_length
        line_index += 1
        if line_index < number_of_streamlines:
            line_length = lines[i + line_index]

    # #
    # # create header
    # #
    # hdr = {'vox_to_ras':np.eye(4),
    #        'voxel_size':np.ones(3),
    #        'dim':np.array([256,256,256]),
    #        'scalar_name':scalar_names,
    #        'property_name':property_names}

    tractogram = nibabel.streamlines.tractogram.Tractogram(
        streamlines, affine_to_rasmm=np.eye(4))
    tck = nibabel.streamlines.tck.TckFile(tractogram)

    with open(output, 'wb') as f:
        # nibabel.trackvis.write(f, streamlines, hdr)
        tck.save(f)
Beispiel #32
0
    def find_plane_mesh_intersection(mesh,
                                     proj,
                                     use_vtk_for_intersection=True):

        # Find axis orthogonal to the projection of interest
        axis = [a for a in [0, 1, 2] if a not in proj][0]

        # Get all mesh points
        points = vtknp.vtk_to_numpy(mesh.GetPoints().GetData())

        if not np.abs(points[:, axis]).sum():
            raise Exception("Only zeros found in the plane axis.")

        if use_vtk_for_intersection:

            mid = np.mean(points[:, axis])
            '''Set the plane a little off center to avoid undefined intersections.
            Without this the code hangs when the mesh has any edge aligned with the
            projection plane. Also add a little of noisy to the coordinates to
            help with the same problem.'''
            mid += 0.75
            offset = 0.1 * np.ptp(points, axis=0).max()

            # Create a vtkPlaneSource
            plane = vtk.vtkPlaneSource()
            plane.SetXResolution(4)
            plane.SetYResolution(4)
            if axis == 0:
                plane.SetOrigin(mid, points[:, 1].min() - offset,
                                points[:, 2].min() - offset)
                plane.SetPoint1(mid, points[:, 1].min() - offset,
                                points[:, 2].max() + offset)
                plane.SetPoint2(mid, points[:, 1].max() + offset,
                                points[:, 2].min() - offset)
            if axis == 1:
                plane.SetOrigin(points[:, 0].min() - offset, mid,
                                points[:, 2].min() - offset)
                plane.SetPoint1(points[:, 0].min() - offset, mid,
                                points[:, 2].max() + offset)
                plane.SetPoint2(points[:, 0].max() + offset, mid,
                                points[:, 2].min() - offset)
            if axis == 2:
                plane.SetOrigin(points[:, 0].min() - offset,
                                points[:, 1].min() - offset, mid)
                plane.SetPoint1(points[:, 0].min() - offset,
                                points[:, 1].max() + offset, mid)
                plane.SetPoint2(points[:, 0].max() + offset,
                                points[:, 1].min() - offset, mid)
            plane.Update()
            plane = plane.GetOutput()

            # Trangulate the plane
            triangulate = vtk.vtkTriangleFilter()
            triangulate.SetInputData(plane)
            triangulate.Update()
            plane = triangulate.GetOutput()

            # Calculate intersection
            intersection = vtk.vtkIntersectionPolyDataFilter()
            intersection.SetInputData(0, mesh)
            intersection.SetInputData(1, plane)
            intersection.Update()
            intersection = intersection.GetOutput()

            # Get coordinates of intersecting points
            points = vtknp.vtk_to_numpy(intersection.GetPoints().GetData())
            coords = points[:, proj]

        else:

            valids = np.where((points[:, axis] > -2.5)
                              & (points[:, axis] < 2.5))
            coords = points[valids[0]][:, proj]

        # Sorting points clockwise
        # This has been discussed here:
        # https://stackoverflow.com/questions/51074984/sorting-according-to-clockwise-point-coordinates/51075469
        # but seems not to be very efficient. Better version is proposed here:
        # https://stackoverflow.com/questions/57566806/how-to-arrange-the-huge-list-of-2d-coordinates-in-a-clokwise-direction-in-python
        center = tuple(
            map(
                operator.truediv,
                reduce(lambda x, y: map(operator.add, x, y), coords),
                [len(coords)] * 2,
            ))
        coords = sorted(
            coords,
            key=lambda coord: (-135 - math.degrees(
                math.atan2(*tuple(map(operator.sub, coord, center))[::-1]))) %
            360,
        )

        # Store sorted coordinates
        # points[:, proj] = coords
        return np.array(coords)
Beispiel #33
0
def vtkcontourfgrid(cutMapper, pl3d_output, src_output, var_name, levels,
                    snapshot_dir, plane_normal, scalarRange):

    #    if not X_is_running():
    #       return

    #off-screen rendering
    #gfac = vtk.vtkGraphicsFactory
    #gfac.SetOffScreenOnlyMode(1)
    #gfac.SetUseMesaClasses(1)
    #im_fac = vtk.vtkImagingFactory
    #im_fac.SetUseMesaClasses(1)

    pl3d_output.GetPointData().SetActiveScalars(var_name)
    if (scalarRange == (0, 0)):

        #print scalarRange

        # this prevents zero values from setting colourbar
        scalarnump = VN.vtk_to_numpy(
            src_output.GetPointData().GetScalars(var_name))
        minval = np.amin(scalarnump)
        try:
            if (minval >= 0.0):
                minval = np.amin(scalarnump[scalarnump > 0.0])
        except Exception:
            pass
        maxval = np.amax(scalarnump)
        scalarRange = (minval, maxval)
        #print scalarRange

        #scalarRange =pl3d_output.GetPointData().GetScalars(var_name).GetRange()

    cutMapper.SetScalarRange(scalarRange)
    cutActor = vtk.vtkActor()
    cutActor.SetMapper(cutMapper)

    lut = vtk.vtkLookupTable()  #MakeLUT()
    lut.SetNumberOfTableValues(levels)
    lut.SetHueRange(0.667, 0.0)
    lut.SetNanColor(1, 0, 0, 1)
    lut.Build()
    cutMapper.SetLookupTable(lut)

    scalarBar = vtk.vtkScalarBarActor()
    scalarBar.SetLookupTable(lut)
    scalarBar.SetTitle(var_name)

    # Add the actors to the renderer, set the background and size
    #ren.AddActor(outlineActor)
    #ren.AddActor(planeActor)
    # Create the RenderWindow, Renderer and both Actors
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.SetOffScreenRendering(1)  #off-screen render
    renWin.AddRenderer(ren)
    #iren = vtk.vtkRenderWindowInteractor()
    #iren.SetRenderWindow(renWin)
    ren.AddActor(cutActor)
    ren.AddActor2D(scalarBar)

    ren.SetBackground(0, 0, 0)
    renWin.SetSize(2800, 1600)

    camera = vtk.vtkCamera()
    camera.SetPosition(plane_normal)
    ren.SetActiveCamera(camera)

    #zoom
    ren.ResetCamera()
    ren.GetActiveCamera().Zoom(0.9)
    ren.GetActiveCamera().Dolly(1.4)
    ren.ResetCameraClippingRange()

    #off-screen
    renWin.Render()
    win2im = vtk.vtkWindowToImageFilter()
    win2im.SetInput(renWin)
    win2im.Update()
    writer = vtk.vtkPNGWriter()
    writer.SetFileName(snapshot_dir + '.png')
    writer.SetInputConnection(win2im.GetOutputPort())
    writer.Write()
Beispiel #34
0
def main(sysargs):
    # handle arguments
    parser = argparse.ArgumentParser('Process args')
    parser.add_argument('--inputDWI', required=True, type=str)
    parser.add_argument('--bvalues', required=True, type=str)
    parser.add_argument('--tolerance', required=True, type=float)
    parser.add_argument('--outputDWI', required=True, type=str)
    args = parser.parse_args(sysargs)

    dwifile = args.inputDWI
    outfile = args.outputDWI
    target_bvals = map(float, args.bvalues.split(','))
    bval_tolerance = args.tolerance

    # load data
    sn = slicer.vtkMRMLNRRDStorageNode()
    sn.SetFileName(dwifile)
    node_in = mrml.vtkMRMLDiffusionWeightedVolumeNode()
    print("loading: ", dwifile)
    sn.ReadData(node_in)
    dwi_in = slicer.util.arrayFromVolume(node_in)

    # sanity check that the last axis is volumes
    assert (node_in.GetNumberOfGradients() == dwi_in.shape[-1]
            ), "Number of gradients do not match the size of last image axis!"

    bvals_in = numpy_support.vtk_to_numpy(node_in.GetBValues())
    grads_in = numpy_support.vtk_to_numpy(node_in.GetDiffusionGradients())
    for (i, g) in enumerate(grads_in):
        norm = np.linalg.norm(g)
        if norm > 1e-6: grads_in[i] = g * 1 / norm

    print("  input gradients: ")
    print(grads_in)
    print("  input bvals: ")
    print(bvals_in)

    # select the indices to keep based on b value
    indices = []
    for (i, bval) in enumerate(bvals_in):
        for check_bval in target_bvals:
            if abs(bval - check_bval) < bval_tolerance:
                indices.append(i)

    print("selected indices: ", indices)

    # output shape: (3d_vol_shape..., num_indices)
    num_indices = len(indices)
    shape_out = dwi_in.shape[:-1] + (num_indices, )
    print("input shape: ", dwi_in.shape)
    print("output shape: ", shape_out)

    # construct output subset
    vol_out = np.zeros(shape_out, dtype=dwi_in.dtype)
    grads_out = np.zeros((num_indices, 3))
    bvals_out = np.zeros(num_indices)

    for (new_i, index) in enumerate(indices):
        vol_out[:, :, :, new_i] = dwi_in[:, :, :, index]
        grads_out[new_i, :] = grads_in[index, :]
        bvals_out[new_i] = bvals_in[index]

    print("selected bvals: ", bvals_out)
    print("  grads_out shape: ", grads_out.shape)
    print("  vol_out shape:   ", vol_out.shape)

    # write output
    sn_out = slicer.vtkMRMLNRRDStorageNode()
    sn_out.SetFileName(outfile)
    node_out = mrml.vtkMRMLDiffusionWeightedVolumeNode()

    # copy image information
    node_out.Copy(node_in)
    # reset the attribute dictionary, otherwise it will be transferred over
    attrs = vtk.vtkStringArray()
    node_out.GetAttributeNames(attrs)
    for i in xrange(0, attrs.GetNumberOfValues()):
        node_out.SetAttribute(attrs.GetValue(i), None)

    # reset the data array to force resizing, otherwise we will just keep the old data too
    node_out.SetAndObserveImageData(None)
    slicer.util.updateVolumeFromArray(node_out, vol_out)
    node_out.SetNumberOfGradients(num_indices)
    node_out.SetBValues(numpy_support.numpy_to_vtk(bvals_out))
    node_out.SetDiffusionGradients(numpy_support.numpy_to_vtk(grads_out))
    node_out.Modified()

    sn_out.WriteData(node_out)
Beispiel #35
0
from vtk.util import numpy_support as VN

reader = vtkStructuredPointsReader()
reader.SetFileName('../../../temp/bb480.vtk')
reader.ReadAllVectorsOn()
reader.ReadAllScalarsOn()
reader.Update()

data = reader.GetOutput()

dim = data.GetDimensions()
vec = list(dim)
vec = [i - 1 for i in dim]
vec.append(3)

u = VN.vtk_to_numpy(data.GetCellData().GetArray('velocity'))
b = VN.vtk_to_numpy(data.GetCellData().GetArray('cell_centered_B'))

u = u.reshape(vec, order='F')
b = b.reshape(vec, order='F')

x = zeros(data.GetNumberOfPoints())
y = zeros(data.GetNumberOfPoints())
z = zeros(data.GetNumberOfPoints())

for i in range(data.GetNumberOfPoints()):
    x[i], y[i], z[i] = data.GetPoint(i)

x = x.reshape(dim, order='F')
y = y.reshape(dim, order='F')
z = z.reshape(dim, order='F')
Beispiel #36
0
 def getter(self):
     colors = getattr(self.vtk_polydata, "Get{}Data".format(vtk_name))().GetScalars()
     if colors is None:
         return
     return vtk_to_numpy(colors)
Beispiel #37
0
#renderer.TwoSidedLightingOff()
#renderer.LightFollowCameraOff()
renderer.AddLight(light1)
renderer.AddLight(light2)
renderer.AddLight(light3)
renderWindow.Render()

vtkwin_im = vtk.vtkWindowToImageFilter()
vtkwin_im.SetInput(renderWindow)
vtkwin_im.Update()

vtk_image = vtkwin_im.GetOutput()
height, width, _ = vtk_image.GetDimensions()
vtk_array = vtk_image.GetPointData().GetScalars()
components = vtk_array.GetNumberOfComponents()
arr = vtk_to_numpy(vtk_array).reshape(height, width, components)
"""
vrml_exporter = vtk.vtkVRMLExporter()
vrml_exporter.SetInput(renderWindow)
vrml_exporter.SetFileName('test.wrl')
vrml_exporter.Write()

obj_exporter = vtk.vtkOBJExporter()
obj_exporter.SetInput(renderWindow)
obj_exporter.SetFilePrefix('test')
obj_exporter.Write()
"""

renderWindowInteractor.Start()

renderWindowInteractor.GetRenderWindow().Finalize()
Beispiel #38
0
import numpy as np
import matplotlib.pyplot as plt

import seaborn as sns

sns.set()

if __name__ == "__main__":
    input_folder = "/home/steven/scriptie/inputs/sphere_r_100_p_20"

    imgdata = vtk_functions.folder_to_imgdata(input_folder)

    sigma = 3

    if sigma > 0:
        padding = sigma * 2
        imgdata = vtk_functions.pad_imgdata(imgdata, padding)
        imgdata = vtk_functions.gauss_imgdata(imgdata, sigma=sigma)

    polydata = vtk_functions.imgdata_to_pd(imgdata)
    polydata = vtk_functions.normals(polydata)
    polydata = vtk_functions.mean_curvature(polydata)

    k = numpy_support.vtk_to_numpy(
        polydata.GetPointData().GetArray("Mean_Curvature"))

    print(len(k))

    ax = sns.distplot(k)
    plt.show()
Beispiel #39
0
 def points(self):
     """ returns a pointer to the points as a numpy object """
     vtk_data = self.GetPoints().GetData()
     arr = vtk_to_numpy(vtk_data)
     return pyvista_ndarray(arr, vtk_data)
Beispiel #40
0
 def t_coords(self):
     """The active texture coordinates on the points"""
     if self.GetPointData().GetTCoords() is not None:
         return vtk_to_numpy(self.GetPointData().GetTCoords())
     return None
Beispiel #41
0
y_half *= scale_factor
z_half *= scale_factor

x_range = x_full
y_range = y_half * 2
z_range = z_half * 2

from vtk.util import numpy_support

grids = []
for i in range(int(vv.app.scene.EndTime) + 1):
    vv.app.scene.AnimationTime = i
    grid = np.zeros((x_range, y_range, z_range))

    #pts = np.fromfile(pc_file, np.float32, -1).reshape((-1, 4))
    pts = numpy_support.vtk_to_numpy(poly.GetPoints().GetData())

    pts = pts[:, :3] * scale_factor
    pts += [0, y_half, z_half]
    pts = np.round(pts).astype(int)
    pts = pts[pts[:, 0] >= 0]
    pts = pts[pts[:, 0] < x_full]
    pts = pts[pts[:, 1] >= 0]
    pts = pts[pts[:, 1] < y_range]
    pts = pts[pts[:, 2] >= 0]
    pts = pts[pts[:, 2] < z_range]

    grid[pts[:, 0], pts[:, 1], pts[:, 2]] = 1
    grids.append(grid)

#for i in range(1, len(grids)):
Beispiel #42
0
def bitmap2memmap(files, slice_size, orientation, spacing, resolution_percentage):
    """
    From a list of dicom files it creates memmap file in the temp folder and
    returns it and its related filename.
    """
    message = _("Generating multiplanar visualization...")
    if len(files) > 1:
        update_progress= vtk_utils.ShowProgress(len(files) - 1, dialog_type = "ProgressDialog")

    temp_file = tempfile.mktemp()

    if orientation == 'SAGITTAL':
        if resolution_percentage == 1.0:
            shape = slice_size[1], slice_size[0], len(files)
        else:
            shape = math.ceil(slice_size[1]*resolution_percentage),\
                    math.ceil(slice_size[0]*resolution_percentage), len(files)

    elif orientation == 'CORONAL':
        if resolution_percentage == 1.0:
            shape = slice_size[1], len(files), slice_size[0]
        else:
            shape = math.ceil(slice_size[1]*resolution_percentage), len(files),\
                                        math.ceil(slice_size[0]*resolution_percentage)
    else:
        if resolution_percentage == 1.0:
            shape = len(files), slice_size[1], slice_size[0]
        else:
            shape = len(files), math.ceil(slice_size[1]*resolution_percentage),\
                                        math.ceil(slice_size[0]*resolution_percentage)


    if resolution_percentage == 1.0:
        matrix = numpy.memmap(temp_file, mode='w+', dtype='int16', shape=shape)
    
    cont = 0
    max_scalar = None
    min_scalar = None

    xy_shape = None
    first_resample_entry = False

    for n, f in enumerate(files):
        image_as_array = bitmap_reader.ReadBitmap(f)

        image = converters.to_vtk(image_as_array, spacing=spacing,\
                                    slice_number=1, orientation=orientation.upper())

        if resolution_percentage != 1.0:
            
            
            image_resized = ResampleImage2D(image, px=None, py=None,\
                                resolution_percentage = resolution_percentage, update_progress = None)

            yx_shape = image_resized.GetDimensions()[1], image_resized.GetDimensions()[0]


            if not(first_resample_entry):
                shape = shape[0], yx_shape[0], yx_shape[1] 
                matrix = numpy.memmap(temp_file, mode='w+', dtype='int16', shape=shape)
                first_resample_entry = True

            image = image_resized

        min_aux, max_aux = image.GetScalarRange()
        if min_scalar is None or min_aux < min_scalar:
            min_scalar = min_aux

        if max_scalar is None or max_aux > max_scalar:
            max_scalar = max_aux

        array = numpy_support.vtk_to_numpy(image.GetPointData().GetScalars())

        if array.dtype == 'uint16':
            array = array - 32768/2
       
        array = array.astype("int16")

        if orientation == 'CORONAL':
            array.shape = matrix.shape[0], matrix.shape[2]
            matrix[:, n, :] = array[:,::-1]
        elif orientation == 'SAGITTAL':
            array.shape = matrix.shape[0], matrix.shape[1]
            # TODO: Verify if it's necessary to add the slices swapped only in
            # sagittal rmi or only in # Rasiane's case or is necessary in all
            # sagittal cases.
            matrix[:, :, n] = array[:,::-1]
        else:
            array.shape = matrix.shape[1], matrix.shape[2]
            matrix[n] = array
        
        if len(files) > 1:
            update_progress(cont,message)
        cont += 1

    matrix.flush()
    scalar_range = min_scalar, max_scalar

    print("MATRIX", matrix.shape)
    return matrix, scalar_range, temp_file
 def test_pointdata(self):
     self.nrrdArray = ns.vtk_to_numpy(
         self.rnrrd.GetOutput().GetPointData().GetTensors())
     self.itkArray = ns.vtk_to_numpy(
         self.ritk.GetOutput().GetPointData().GetTensors())
     self.assertTrue(numpy.allclose(self.nrrdArray, self.itkArray))
    # gh_b = (np.percentile(b_distarray,100) - np.percentile(b_distarray,75))/np.percentile(b_distarray,100)
    # b_rim_qartile1 = np.percentile(b_distarray, 25)
    # b_rim_qartile2 = np.percentile(b_distarray, 50)
    # b_rim_qartile3 = np.percentile(b_distarray, 75)
    #
    # # print(b_distarray)
    # # print("Mean: " +str(np.mean(b_distarray)))
    # # print("Median: " +str(np.median(b_distarray)))
    # # print("Min: " +str(np.min(b_distarray)))
    # # print("Max: " +str(np.max(b_distarray)))
    # # n, bins, patches = plt.hist(b_distarray) #, 50, normed=1, facecolor='green', alpha=0.75)
    # # plt.show()

    n_pt = surfdist_n.GetPointData()
    n_distscalars = n_pt.GetScalars()
    n_distarray = numpy_support.vtk_to_numpy(n_distscalars)
    n_distarray_clipped = n_distarray[n_distarray > 0]

    gh_n_clipped = (np.percentile(n_distarray_clipped,100) - np.percentile(n_distarray_clipped,75))/np.percentile(n_distarray_clipped,100)
    n_rim_qartile1_clipped = np.percentile(n_distarray_clipped, 25)
    n_rim_qartile2_clipped = np.percentile(n_distarray_clipped, 50)
    n_rim_qartile3_clipped = np.percentile(n_distarray_clipped, 75)

    gh_n = (np.percentile(n_distarray,100) - np.percentile(n_distarray,75))/np.percentile(n_distarray,100)
    n_rim_qartile1 = np.percentile(n_distarray, 25)
    n_rim_qartile2 = np.percentile(n_distarray, 50)
    n_rim_qartile3 = np.percentile(n_distarray, 75)

    csvline = currentline + [n_necroticvol, n_edemavol, n_enhvol, n_enhrimwidth, gh_n, n_rim_qartile1, n_rim_qartile2, n_rim_qartile3, gh_n_clipped, n_rim_qartile1_clipped, n_rim_qartile2_clipped, n_rim_qartile3_clipped]
   # csvline = currentline + [gtnecroticvol, gtedemavol, gtenhvol, gtenhrimwidth, gh_gt, gt_rim_qartile1, gt_rim_qartile2, gt_rim_qartile3, gh_gt_clipped, gt_rim_qartile1_clipped, gt_rim_qartile2_clipped, gt_rim_qartile3_clipped,
   #                           b_necroticvol, b_edemavol, b_enhvol, b_enhrimwidth, gh_b, b_rim_qartile1, b_rim_qartile2, b_rim_qartile3, gh_b_clipped, b_rim_qartile1_clipped, b_rim_qartile2_clipped, b_rim_qartile3_clipped,
Beispiel #45
0
    def __init__(self, dataDir='data', streamFile='stream.vtk'):
        """
        Read the initial streamlines.
        
        call signature:
        
          readStream(dataDir = 'data', streamFile = 'stream.vtk')
          
        Keyword arguments:
         *dataDir*:
            Data directory.
            
         *streamFile*:
            Read the initial streamline from this file.
        """

        # load the data
        reader = vtk.vtkPolyDataReader()
        reader.SetFileName(dataDir + '/' + streamFile)
        reader.Update()
        output = reader.GetOutput()

        # get the fields
        field = output.GetFieldData()
        nArrays = field.GetNumberOfArrays()

        class params:
            pass

        p = params()
        for i in range(nArrays):
            arrayName = field.GetArrayName(i)
            if any(arrayName == np.array(['l', 'sl'])):
                setattr(self, arrayName,
                        VN.vtk_to_numpy(field.GetArray(arrayName)))
            elif any(arrayName == np.array(
                ['hMin', 'hMax', 'lMax', 'tol', 'iterMax', 'nt'])):
                setattr(self, arrayName,
                        VN.vtk_to_numpy(field.GetArray(arrayName))[0])
            else:
                # change this if parameters can have more than one entry
                setattr(p, arrayName,
                        VN.vtk_to_numpy(field.GetArray(arrayName))[0])
        setattr(self, 'p', p)

        # get the points
        points = output.GetPoints()
        pointsData = points.GetData()
        data = VN.vtk_to_numpy(pointsData)
        #data = np.swapaxes(data, 0, 1)
        print self.nt
        print self.sl
        print data.shape
        tracers = np.zeros([self.nt, np.max(self.sl), 3], dtype=data.dtype)
        sl = 0
        for i in range(self.nt):
            #if (i > 0):
            #sl = self.sl[i-1]
            #else:
            #sl = 0
            print sl, self.sl[i]
            tracers[i, :self.sl[i], :] = data[sl:sl + self.sl[i], :]
            sl += self.sl[i]
        setattr(self, 'tracers', tracers)
Beispiel #46
0
    def extractfeatures_inside(self, DICOMImages, image_pos_pat, image_ori_pat, series_path, phases_series, VOI_mesh):
        """ Start pixVals for collection pixel values at VOI """
        pixVals = []
        deltaS = {}
        
        # necessary to read point coords
        VOIPnt = [0,0,0]
        ijk = [0,0,0]
        pco = [0,0,0]
        
        for i in range(len(DICOMImages)):
            abspath_PhaseID = series_path+os.sep+str(phases_series[i]) 
            print phases_series[i]
            
            # Get total number of files
            load = Inputs_init()
            [len_listSeries_files, FileNms_slices_sorted_stack] = load.ReadDicomfiles(abspath_PhaseID)
            mostleft_slice = FileNms_slices_sorted_stack.slices[0]
            
            # Get dicom header, retrieve
            dicomInfo_series = dicom.read_file(abspath_PhaseID+os.sep+str(mostleft_slice)) 
            
            # (0008,0031) AT S Series Time            # hh.mm.ss.frac
            seriesTime = str(dicomInfo_series[0x0008,0x0031].value) 
            # (0008,0033) AT S Image Time             # hh.mm.ss.frac
            imageTime = str(dicomInfo_series[0x0008,0x0033].value)
            
            # (0008,0032) AT S Acquisition Time       # hh.mm.ss.frac
            ti = str(dicomInfo_series[0x0008,0x0032].value) 
            
            acquisitionTimepoint = datetime.time(hour=int(ti[0:2]), minute=int(ti[2:4]), second=int(ti[4:6]))
            self.timepoints.append( datetime.datetime.combine(datetime.date.today(), acquisitionTimepoint) )
            
            # find mapping to Dicom space  
            [transformed_image, transform_cube] = Display().dicomTransform(DICOMImages[i], image_pos_pat, image_ori_pat)
            
            ### Get inside of VOI            
            [VOI_scalars, VOIdims] = self.createMaskfromMesh(VOI_mesh, transformed_image)
            print "\n VOIdims"
            print VOIdims
            
            # get non zero elements
            image_scalars = transformed_image.GetPointData().GetScalars()
            numpy_VOI_imagedata = vtk_to_numpy(image_scalars)     
            
            numpy_VOI_imagedata = numpy_VOI_imagedata.reshape(VOIdims[2], VOIdims[1], VOIdims[0]) 
            numpy_VOI_imagedata = numpy_VOI_imagedata.transpose(2,1,0)
            
            print "Shape of VOI_imagedata: "
            print numpy_VOI_imagedata.shape
            
            #################### HERE GET IT AND MASK IT OUT
            self.nonzeroVOIextracted = nonzero(VOI_scalars)
            print self.nonzeroVOIextracted
            
            VOI_imagedata = numpy_VOI_imagedata[self.nonzeroVOIextracted]     
            
            print "shape of VOI_imagedata  Clipped:"
            print VOI_imagedata.shape
        
            for j in range( len(VOI_imagedata) ):
                pixValx = VOI_imagedata[j]
                pixVals.append(pixValx)
                        
            # Now collect pixVals
            print "Saving %s" % 'delta'+str(i)
            deltaS['delta'+str(i)] = pixVals
            pixVals = []
                    
        print self.timepoints
        
        # Collecting timepoints in proper format
        t_delta = []
        t_delta.append(0)
        total_time = 0
        for i in range(len(DICOMImages)-1):
            current_time = self.timepoints[i+1]
            previous_time = self.timepoints[i]
            difference_time =current_time - previous_time
            timestop = divmod(difference_time.total_seconds(), 60)
            t_delta.append( t_delta[i] + timestop[0]+timestop[1]*(1./60))
            total_time = total_time+timestop[0]+timestop[1]*(1./60)
            
        # finally print t_delta
        print t_delta
        t = array(t_delta)
        print "total_time"
        print total_time
        
        ##############################################################
        # Finished sampling deltaS
        # APply lmfit to deltaS
        # first sample the mean
        data_deltaS = []; t_deltaS = []; mean_deltaS = []; sd_deltaS = []; se_deltaS = []; n_deltaS = []
        
        # append So and to
        data_deltaS.append( 0 )       
        t_deltaS.append(0)
        mean_deltaS.append( mean(deltaS['delta0']) )
        sd_deltaS.append(0)
        se_deltaS.append(0)
        n_deltaS.append( len(deltaS['delta0']) )
        
        for k in range(1,len(DICOMImages)):
            deltaS_i =  ( mean(array(deltaS['delta'+str(k)]).astype(float)) -  mean(deltaS['delta0']) )/  mean(deltaS['delta0'])
            data_deltaS.append( deltaS_i )
            t_deltaS.append(k)
            print 'delta'+str(k)
            print  data_deltaS[k]
            
            ##############################################################
            # Calculate data_error
            # estimate the population mean and SD from our samples to find SE
            # SE tells us the distribution of individual scores around the sampled mean.
            mean_deltaS_i = mean(array(deltaS['delta'+str(k)]))
            std_deltaS_i = std(array(deltaS['delta'+str(k)]))
            n_deltaS_i = len(array(deltaS['delta'+str(k)]))
                
            sd_deltaS.append( std_deltaS_i )
            mean_deltaS.append( mean_deltaS_i )
            
            # Standard Error of the mean SE
            # the smaller the variability in the data, the more confident we are that one value (the mean) accurately reflects them.
            se_deltaS.append(std_deltaS_i/sqrt(n_deltaS_i))
            n_deltaS.append(n_deltaS_i)
                        
        # make array for data_deltaS
        data = array(data_deltaS)
        
        print "\n================\nMean and SE (i.e VOI sample data)"
        print mean_deltaS
        print se_deltaS
        
        # create a set of Parameters
        params = Parameters()
        params.add('amp',   value= 10,  min=0)
        params.add('alpha', value= 1, min=0) 
        params.add('beta', value= 0.05, min=0.0001, max=0.9)
        
        # do fit, here with leastsq model
        # define objective function: returns the array to be minimized
        def fcn2min(params, t, data):
            global model, model_res, x
            """ model EMM for Bilateral DCE-MRI, subtract data"""
            # unpack parameters:
            #  extract .value attribute for each parameter
            amp = params['amp'].value    # Upper limit of deltaS
            alpha = params['alpha'].value    # rate of signal increase min-1
            beta = params['beta'].value        # rate of signal decrease min-1
                    
            model = amp * (1- exp(-alpha*t)) * exp(-beta*t)
            
            x = linspace(0, t[4], 101)
            model_res = amp * (1- exp(-alpha*x)) * exp(-beta*x)
        
            return model - data
        
        #####
        myfit = Minimizer(fcn2min,  params, fcn_args=(t,), fcn_kws={'data':data})
        myfit.prepare_fit()
        myfit.leastsq()
            
        # On a successful fit using the leastsq method, several goodness-of-fit statistics
        # and values related to the uncertainty in the fitted variables will be calculated
        print "myfit.success"
        print myfit.success
        print "myfit.residual"
        print myfit.residual
        print "myfit.chisqr"
        print myfit.chisqr
        print "myfit.redchi"
        print myfit.redchi
            
        # calculate final result
        final = data + myfit.residual
        # write error report
        report_errors(params)
        
        # Calculate R-square
        # R_square = sum( y_fitted - y_mean)/ sum(y_data - y_mean)
        R_square = sum( (model - mean(data))**2 )/ sum( (data - mean(data))**2 )
        print "R^2"
        print R_square
        
        self.amp = params['amp'].value
        self.alpha = params['alpha'].value
        self.beta = params['beta'].value
        
        ##################################################
        # Now Calculate Extract parameters from model
        self.iAUC1 = params['amp'].value *( ((1-exp(-params['beta'].value*t[1]))/params['beta'].value) + (exp((-params['alpha'].value+params['beta'].value)*t[1])-1)/(params['alpha'].value+params['beta'].value) )
        print "iAUC1"
        print self.iAUC1
        
        self.Slope_ini = params['amp'].value*params['alpha'].value
        print "Slope_ini"
        print self.Slope_ini
    
        self.Tpeak = (1/params['alpha'].value)*log(1+(params['alpha'].value/params['beta'].value))
        print "Tpeak"
        print self.Tpeak
    
        self.Kpeak = -params['amp'].value * params['alpha'].value * params['beta'].value
        print "Kpeak"
        print self.Kpeak
    
        self.SER = exp( (t[4]-t[1])*params['beta'].value) * ( (1-exp(-params['alpha'].value*t[1]))/(1-exp(-params['alpha'].value*t[4])) )
        print "SER"
        print self.SER
        
        ##################################################
        # Now Calculate enhancement Kinetic based features
        # Based on the course of signal intensity within the lesion
        print "\n Saving %s" % 'Crk'
        So = array(deltaS['delta0']).astype(float)
        Crk = {'Cr0': mean(So)}  
        C = {}
        Carray = []
        
        for k in range(1,len(DICOMImages)):
            Sk = array(deltaS['delta'+str(k)]).astype(float)
            Cr = 0
            for j in range( len(So) ):
                # extract average enhancement over the lesion at each time point
                Cr = Cr + (Sk[j] - So[j])/So[j]
                Carray.append((Sk[j] - So[j])/So[j])
                
            # compile
            C['C'+str(k)] = Carray
            Crk['Cr'+str(k)] = Cr/len(Sk)
        
        # Extract Fii_1
        for k in range(1,5):
            currentCr = array(Crk['Cr'+str(k)]).astype(float)
            print currentCr
            if( self.maxCr < currentCr):
                self.maxCr = float(currentCr)
                self.peakCr = int(k)
                
        print "Maximum Upate (Fii_1) = %d " %  self.maxCr
        print "Peak Cr (Fii_2) = %d " %  self.peakCr
        
        # Uptake rate
        self.UptakeRate = float(self.maxCr/self.peakCr)    
        print "Uptake rate (Fii_3) "
        print self.UptakeRate
        
        # WashOut Rate
        if( self.peakCr == 4):
            self.washoutRate = 0
        else:
            self.washoutRate = float( (self.maxCr - array(Crk['Cr'+str(4)]).astype(float))/(4-self.peakCr) )
        print "WashOut rate (Fii_4) "
        print self.washoutRate


        ##################################################
        # Now Calculate enhancement-variance Kinetic based features
        # Based on Crk['Cr'+str(k)] = Cr/len(Sk)
        print "\n Saving %s" % 'Vrk'
        Vrk = {}
        
        for k in range(1,5):
            Ci = array(C['C'+str(k)]).astype(float)    
            Cri = array(Crk['Cr'+str(k)]).astype(float)
            Vr = 0
            for j in range( len(Ci) ):
                # extract average enhancement over the lesion at each time point
                Vr = Vr + (Ci[j] - Cri)**2
            # compile
            Vrk['Vr'+str(k)] = Vr/(len(Ci)-1)
        
        # Extract Fiii_1
        for k in range(1,5):
            currentVr = array(Vrk['Vr'+str(k)]).astype(float)
            if( self.maxVr < currentVr):
                print currentVr
                self.maxVr = float(currentVr)
                self.peakVr = int(k)
        
        print "Maximum Variation of enhan (Fiii_1) = %d " %  self.maxVr
        print "Peak Vr (Fii_2) = %d " %  self.peakVr
        
        # Vr_increasingRate 
        self.Vr_increasingRate = self.maxVr/self.peakVr    
        print "Vr_increasingRate (Fiii_3)" 
        print self.Vr_increasingRate
        
        # Vr_decreasingRate
        if( self.peakVr == 4):
            Vr_decreasingRate = 0
        else:
            Vr_decreasingRate = float((self.maxVr - array(Vrk['Vr'+str(4)]).astype(float))/(4-self.peakVr))
        print "Vr_decreasingRate (Fiii_4) "
        print Vr_decreasingRate
        
        # Vr_post_1 
        self.Vr_post_1 = float( array(Vrk['Vr'+str(1)]).astype(float))
        print "Vr_post_1 (Fiii_5)"
        print self.Vr_post_1
 
        ##################################################
        # orgamize into dataframe
        self.dynamicEMM_inside = DataFrame( data=array([[ self.amp, self.alpha, self.beta, self.iAUC1, self.Slope_ini, self.Tpeak, self.Kpeak, self.SER, self.maxCr, self.peakCr, self.UptakeRate, self.washoutRate, self.maxVr, self.peakVr, self.Vr_increasingRate, self.Vr_post_1]]), 
                                columns=['A.inside', 'alpha.inside', 'beta.inside', 'iAUC1.inside', 'Slope_ini.inside', 'Tpeak.inside', 'Kpeak.inside', 'SER.inside', 'maxCr.inside', 'peakCr.inside', 'UptakeRate.inside', 'washoutRate.inside', 'maxVr.inside', 'peakVr.inside','Vr_increasingRate.inside', 'Vr_post_1.inside'])

        #############################################################
        # try to plot results
        pylab.figure()
        pylab.errorbar(t, data, yerr=se_deltaS, fmt='ro', label='data+SE') # data 'ro' red dots as markers
        pylab.plot(t, final, 'b+', label='data+residuals')    # data+residuals 'b+' blue pluses
        pylab.plot(t, model, 'b', label='model')    # model fit 'b' blue
        pylab.plot(x, model_res, 'k', label='model fit')    # model fit 'k' blakc
        pylab.xlabel(" post-contrast time (min)")
        pylab.ylabel("delta S(t)")
        pylab.legend()
        
        return self.dynamicEMM_inside
Beispiel #47
0
 def points(self):
     points = self.vtk_polydata.GetPoints()
     if points is None:
         return None
     else:
         return vtk_to_numpy(points.GetData())
#to be adapted
namefile = pathbase+'/RUNS_'+args[0]+'/run_OPTIM_Ga'+str(Ga)+'_Rcg'+str(Rcg)+'_Rdhdt'+str(Rdhdt)+'/mesh_'+str(nbparts)+'/'

filespvtu = glob.glob(namefile+'*pvtu')
filespvtu.sort()
filein = filespvtu[-1]

#print filein

#get the vtu data
reader = vtk.vtkXMLPUnstructuredGridReader()
reader.SetFileName(filein)
reader.Update()
output=reader.GetOutput()
PointData=output.GetPointData()#données du nodes
Coords=vtk_to_numpy(output.GetPoints().GetData())

#pour obtenir les indices de nodes a la surface
cellData=output.GetCellData()
pointData=output.GetPointData()
GeometryIDS=vtk_to_numpy(cellData.GetArray(0))

#la condition de borde 1 correspond a la surface
indexGEO=np.where(GeometryIDS==1)

listPoints=set()#pour garde les index
for i in indexGEO[0]:

    celda1=output.GetCell(i)
    ids=celda1.GetPointIds()
    if ids.GetNumberOfIds()==3:#utiliser que les elementes que ont 3 ids == triangles (pas le lignes ou les nodes) 
Beispiel #49
0
from vtk.util import numpy_support
import tracking_filter
reload(tracking_filter)


inp = self.GetInput()
p0 = inp.GetBlock(0)
p1 = inp.GetBlock(1)
t = int(inp.GetInformation().Get(vtk.vtkDataObject.DATA_TIME_STEP()))

# transform PolyData to Numpy array
pts0 = None
pts1 = None
if p0 is not None and p1 is not None:
    pts0 = numpy_support.vtk_to_numpy(p0.GetPoints().GetData())
    pts1 = numpy_support.vtk_to_numpy(p1.GetPoints().GetData())

# run tracking
pts, lines, colors = tracking_filter.run_tracking(pts0, pts1, t)


if pts is not None and lines is not None and colors is not None:
    # numpy to polydata
    poly = vtk.vtkPolyData()
    # points
    points = vtk.vtkPoints()
    points.SetData(numpy_support.numpy_to_vtk(pts, deep=True, array_type=vtk.VTK_FLOAT))       
    poly.SetPoints(points)
    
    # lines
    vtklines = vtk.vtkCellArray()
Beispiel #50
0
 def scale(self):
     return np.linalg.norm(vtk_to_numpy(self.polydata.GetPoints().GetData()), 'fro')
shiftScale.SetInputConnection(reader.GetOutputPort())
shiftScale.Update()

print(reader.GetRescaleSlope())
print(reader.GetRescaleOffset())

# Get the 'vtkImageData' object from the reader
imageData = reader.GetOutput()
# Get the 'vtkPointData' object from the 'vtkImageData' object
pointData = imageData.GetPointData()
# Ensure that only one array exists within the 'vtkPointData' object
assert (pointData.GetNumberOfArrays() == 1)
# Get the `vtkArray` (or whatever derived type) which is needed for the `numpy_support.vtk_to_numpy` function
arrayData = pointData.GetArray(0)
# Convert the `vtkArray` to a NumPy array
ArrayDicom = numpy_support.vtk_to_numpy(arrayData)
# Reshape the NumPy array to 3D using 'ConstPixelDims' as a 'shape'
ArrayDicom = ArrayDicom.reshape(ConstPixelDims, order='F')

trace = go.Heatmap(z=numpy.rot90(ArrayDicom[:, 120, :]))
data = [trace]
py.iplot(data, filename='basic-heatmap')

threshold = vtk.vtkImageThreshold()
threshold.SetInputConnection(reader.GetOutputPort())
threshold.ThresholdByLower(400)
threshold.ReplaceInOn()
threshold.SetInValue(0)
threshold.ReplaceOutOn()
threshold.SetOutValue(1)
threshold.Update()
Beispiel #52
0
 def vertices(self):
     return vtk_to_numpy(self.polydata.GetPoints().GetData())
Beispiel #53
0
def vtkcontourf_obj(cutMapper, pl3d_output, src_output, var_name, levels,
                    snapshot_dir, plane_normal, scalarRange, i_d):

    #    if not X_is_running():
    #       return

    #off-screen rendering
    #gfac = vtk.vtkGraphicsFactory
    #gfac.SetOffScreenOnlyMode(1)
    #gfac.SetUseMesaClasses(1)
    #im_fac = vtk.vtkImagingFactory
    #im_fac.SetUseMesaClasses(1)

    pl3d_output.GetPointData().SetActiveScalars(var_name)
    if (scalarRange == (0, 0)):

        #print scalarRange

        # this prevents zero values from setting colourbar
        scalarnump = VN.vtk_to_numpy(
            src_output.GetOutput().GetPointData().GetScalars(var_name))
        minval = np.amin(scalarnump)
        try:
            if (minval >= 0.0):
                minval = np.amin(scalarnump[scalarnump > 0.0])
        except Exception:
            pass
        maxval = np.amax(scalarnump)
        scalarRange = (minval, maxval)
        #print scalarRange

        # set bounds to be symmetric if requested
        if i_d.symmetric:
            if (np.abs(minval) > np.abs(maxval)):
                maxval = -minval
            else:
                minval = -maxval
            scalarRange = (minval, maxval)

        #set minval/maxval to zero if very small
        if (np.abs(minval) < np.finfo(np.float64).eps):
            minval = 0.0
        if (np.abs(maxval) < np.finfo(np.float64).eps):
            minval = 0.0
        scalarRange = (minval, maxval)

        #scalarRange =pl3d_output.GetPointData().GetScalars(var_name).GetRange()
    else:
        minval = scalarRange[0]
        maxval = scalarRange[1]

    cutMapper.SetScalarRange(scalarRange)
    cutActor = vtk.vtkActor()
    cutActor.SetMapper(cutMapper)
    #cutActor.SetMapper(src_output)

    lut = vtk.vtkLookupTable()  #MakeLUT()
    lut.SetNumberOfTableValues(levels)
    if (i_d.colourmap == 'jet'):
        lut.SetHueRange(0.667, 0.0)
    elif (i_d.colourmap == 'viridis'):
        lut.SetHueRange(0.801282320, 0.149576098)
        lut.SetSaturationRange(0.985203081, 0.855085320)
        lut.SetValueRange(0.329415190, 0.993247890)
    lut.SetNanColor(1, 0, 0, 1)
    lut.Build()
    cutMapper.SetLookupTable(lut)

    scalarBar = vtk.vtkScalarBarActor()
    scalarBar.SetLookupTable(lut)
    scalarBar.SetTitle(var_name)
    absmax = np.amax([np.abs(minval), np.abs(maxval)])
    if (absmax < 1000 and absmax > .1):
        scalarBar.SetLabelFormat("%-#3.2f")
    elif (absmax < .1):
        scalarBar.SetLabelFormat("%-#3.2e")
    tprop = vtk.vtkTextProperty()
    tprop.SetColor(0, 0, 0)
    #if i_d.non_dimensionalise:
    tprop.SetFontSize(10)
    scalarBar.SetTitleTextProperty(tprop)
    scalarBar.SetLabelTextProperty(tprop)
    scalarBar.SetTextPad(1)

    # Add the actors to the renderer, set the background and size
    #ren.AddActor(outlineActor)
    #ren.AddActor(planeActor)
    # Create the RenderWindow, Renderer and both Actors
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.SetOffScreenRendering(1)  #off-screen render
    renWin.AddRenderer(ren)
    #iren = vtk.vtkRenderWindowInteractor()
    #iren.SetRenderWindow(renWin)
    ren.AddActor(cutActor)
    ren.AddActor2D(scalarBar)

    ren.SetBackground(1, 1, 1)
    renWin.SetSize(i_d.render_size[0], i_d.render_size[1])

    camera = vtk.vtkCamera()
    camera.SetPosition(plane_normal)
    ren.SetActiveCamera(camera)

    #zoom
    ren.ResetCamera()
    ren.GetActiveCamera().Zoom(0.9)
    ren.GetActiveCamera().Dolly(1.4)
    ren.ResetCameraClippingRange()

    #off-screen
    renWin.Render()
    win2im = vtk.vtkWindowToImageFilter()
    win2im.SetInput(renWin)
    win2im.Update()
    writer = vtk.vtkPNGWriter()
    writer.SetFileName(snapshot_dir + '.png')
    writer.SetInputConnection(win2im.GetOutputPort())
    writer.Write()
Beispiel #54
0
def get_inside_point_ids(gui,
                         ugrid,
                         ugrid_flipped,
                         model_name,
                         representation='points'):
    """
    The points that are returned from the frustum, despite being
    defined as inside are not all inside.  The cells are correct
    though.  If you determine the cells outside the volume and the
    points associated with that, and boolean the two, you can find
    the points that are actually inside.

    In other words, ``points`` corresponds to the points inside the
    volume and barely outside.  ``point_ids_flipped`` corresponds to
    the points entirely outside the volume.

    Parameters
    ==========
    ugrid : vtk.vtkUnstructuredGrid()
        the "inside" grid
    ugrid_flipped : vtk.vtkUnstructuredGrid()
        the outside grid

    Returns
    =======
    ugrid : vtk.vtkUnstructuredGrid()
        an updated grid that has the correct points
    nids : (n, ) int ndarray
        the node_ids

    """
    nids = None
    points = ugrid.GetPointData()
    if points is None:
        return ugrid, nids

    ids = points.GetArray('Ids')
    if ids is None:
        return ugrid, nids

    # all points associated with the correctly selected cells are returned
    # but we get extra points for the cells that are inside and out
    point_ids = vtk_to_numpy(ids)
    nids = gui.get_node_ids(model_name, point_ids)

    # these are the points outside the box/frustum (and also include the bad point)
    points_flipped = ugrid_flipped.GetPointData()
    ids_flipped = points_flipped.GetArray('Ids')
    point_ids_flipped = vtk_to_numpy(ids_flipped)
    nids_flipped = gui.get_node_ids(model_name, point_ids_flipped)
    #nids = gui.gui.get_reverse_node_ids(model_name, point_ids_flipped)

    # setA - setB
    nids2 = np.setdiff1d(nids, nids_flipped, assume_unique=True)

    #narrays = points.GetNumberOfArrays()
    #for iarray in range(narrays):
    #name = points.GetArrayName(iarray)
    #print('iarray=%s name=%r' % (iarray, name))

    #------------------
    if representation == 'points':
        # we need to filter the nodes that were filtered by the
        # numpy setdiff1d, so we don't show extra points
        ugrid = create_filtered_point_ugrid(ugrid, nids, nids2)

    nids = nids2
    return ugrid, nids
Beispiel #55
0
def surface2inds(vrtx, trgl, mesh, boundaries=True, internal=True):
    """"
    Function to read gocad polystructure file and output indexes of
    mesh with in the structure.

    """
    import vtk
    import vtk.util.numpy_support as npsup

    # Adjust the index
    trgl = trgl - 1

    # Make vtk pts
    ptsvtk = vtk.vtkPoints()
    ptsvtk.SetData(npsup.numpy_to_vtk(vrtx, deep=1))

    # Make the polygon connection
    polys = vtk.vtkCellArray()
    for face in trgl:
        poly = vtk.vtkPolygon()
        poly.GetPointIds().SetNumberOfIds(len(face))
        for nrv, vert in enumerate(face):
            poly.GetPointIds().SetId(nrv, vert)
        polys.InsertNextCell(poly)

    # Make the polydata, structure of connections and vrtx
    polyData = vtk.vtkPolyData()
    polyData.SetPoints(ptsvtk)
    polyData.SetPolys(polys)

    # Make implicit func
    ImpDistFunc = vtk.vtkImplicitPolyDataDistance()
    ImpDistFunc.SetInput(polyData)

    # Convert the mesh
    vtkMesh = vtk.vtkRectilinearGrid()
    vtkMesh.SetDimensions(mesh.nNx, mesh.nNy, mesh.nNz)
    vtkMesh.SetXCoordinates(npsup.numpy_to_vtk(mesh.vectorNx, deep=1))
    vtkMesh.SetYCoordinates(npsup.numpy_to_vtk(mesh.vectorNy, deep=1))
    vtkMesh.SetZCoordinates(npsup.numpy_to_vtk(mesh.vectorNz, deep=1))
    # Add indexes
    vtkInd = npsup.numpy_to_vtk(np.arange(mesh.nC), deep=1)
    vtkInd.SetName("Index")
    vtkMesh.GetCellData().AddArray(vtkInd)

    extractImpDistRectGridFilt = vtk.vtkExtractGeometry()  # Object constructor
    extractImpDistRectGridFilt.SetImplicitFunction(ImpDistFunc)  #
    extractImpDistRectGridFilt.SetInputData(vtkMesh)

    if boundaries is True:
        extractImpDistRectGridFilt.ExtractBoundaryCellsOn()

    else:
        extractImpDistRectGridFilt.ExtractBoundaryCellsOff()

    if internal is True:
        extractImpDistRectGridFilt.ExtractInsideOn()

    else:
        extractImpDistRectGridFilt.ExtractInsideOff()

    print("Extracting indices from grid...")
    # Executing the pipe
    extractImpDistRectGridFilt.Update()

    # Get index inside
    insideGrid = extractImpDistRectGridFilt.GetOutput()
    insideGrid = npsup.vtk_to_numpy(insideGrid.GetCellData().GetArray("Index"))

    # Return the indexes inside
    return insideGrid
 def __init__(self, filename, cwd=os.getcwd()):
     super().__init__(filename, cwd)
     cell_data = self.grid.GetCellData()
     cell_data_vectors = cell_data.GetVectors()
     self.values = vtk_to_numpy(cell_data_vectors)
Beispiel #57
0
def compute_s2s_error(surface, surfacetarget, nsamples, ofile=''):
    """Compute the symmetric surface-to-surface distance (s2s-metric) for
    surface and surfacetarget. Resample the s2s-array to nsamples."""

    # cap the surfaces to improve surface to surface distance on clipped areas
    surfacecap = capsurface(surface, 'autolabels')
    edges = extractboundaryedge(surfacecap)
    if edges.GetNumberOfPoints() > 0:
        surfacecap = fillholes(surfacecap)

    surfacetargetcap = capsurface(surfacetarget, 'autolabels')
    edges = extractboundaryedge(surfacetargetcap)
    if edges.GetNumberOfPoints() > 0:
        surfacetargetcap = fillholes(surfacetargetcap)

    # compute distances
    seg2gtsurf = surface2surfacedistance(surfacecap, surfacetargetcap, 'S2S')
    gt2segsurf = surface2surfacedistance(surfacetargetcap, surfacecap, 'S2S')

    if ofile:
        writevtp(seg2gtsurf, ofile + 'seg2gt.vtp')
        writevtp(gt2segsurf, ofile + 'gt2seg.vtp')

    # to have ~ same amount of samples per case
    # extract body and pvs
    # re sample to nsamples per case
    indexes = ['body', 'pvs']
    rfrom = {'body': 36, 'pvs': 76}
    rto = {'body': 36, 'pvs': 79}

    # initialise metric dictionary
    s2s_all = {'body': [0.], 'pvs': [0.]}
    for index in indexes:
        # extracting each region
        # including all points
        seg2gtsurf = pointthreshold(seg2gtsurf, 'autolabels', rfrom[index],
                                    rto[index], 1)
        gt2segsurf = pointthreshold(gt2segsurf, 'autolabels', rfrom[index],
                                    rto[index], 1)
        # turning distance array into numpy
        if (seg2gtsurf.GetPointData().GetArray('S2S') != None):
            seg2gtarray = vtk_to_numpy(
                seg2gtsurf.GetPointData().GetArray('S2S'))
        else:
            seg2gtarray = []
        if (gt2segsurf.GetPointData().GetArray('S2S') != None):
            gt2segarray = vtk_to_numpy(
                gt2segsurf.GetPointData().GetArray('S2S'))
        else:
            gt2segarray = []

        # resample to nsamples (unless array smaller than that)
        if len(seg2gtarray) > nsamples:
            seg2gtarray = resamplearray(seg2gtarray, nsamples)
        if len(gt2segarray) > nsamples:
            gt2segarray = resamplearray(gt2segarray, nsamples)

        # concatenate error to have symmetric metric
        superarray = np.concatenate([seg2gtarray, gt2segarray])
        s2s_all[index] = superarray
    return s2s_all
Beispiel #58
0
factors = ['Dach1']
# First, read in the .vtp file for mesh and Dach1
datareader = vtk.vtkXMLImageDataReader()
datareader.SetFileName('test.vti')
datareader.Update()

mesh = vtk.vtkPolyData()
mesh = datareader.GetOutput()

for MF in xrange(0, len(factors)):
    ref = vtk.vtkXMLImageDataReader()
    ref.SetFileName(factors[MF] + '.vti')
    ref.Update()

    # Read your data into another polydata variable for reading

    dach = vtk.vtkPolyData()
    dach = ref.GetOutput()

    # Convert Dach1 and Pressure to micron units and new arrays to point data
    Dach1 = VN.vtk_to_numpy(dach.GetPointData().GetArray('ImageFile'))
    Dach1_numpy = WSS_CONV_FACTOR * Dach1
    Dach1_vtk = VN.numpy_to_vtk(Dach1_numpy)
    Dach1_vtk.SetName(factors[MF])
    mesh.GetPointData().AddArray(Dach1_vtk)

# Write a new .vtp file that has all converted values and mapped values.
w = vtk.vtkXMLImageDataWriter()
w.SetInputData(mesh)
w.SetFileName('E175_H2_ImageData_Combined.vti')
w.Write()
Beispiel #59
0
def compute_forces(vtk_file_path, force_file_path, config_dict):
    """ Function to compute force of a VTK file

    Function 'compute_forces' computes surface forces at points for SU2 result
    files.

    Args:
        vtk_file_path (str): Path of the VTK file
        force_file_path (str): Path to the results force file to write
        config_dict (dict): SU2 cfg file dictionary to dimensionalize
                            non-dimensional output

    Returns:
        mesh (vtkhelpers object instance): Python instance of SU2 result file
                                           with added force and normal vectors
    """

    # To read .vtu file
    reader = vtk.vtkXMLUnstructuredGridReader()  #test
    reader.SetFileName(vtk_file_path)

    # To read .vtk file
    # reader = vtk.vtkUnstructuredGridReader()
    # reader.SetFileName(vtk_file_path)
    # reader.SetReadAllNormals(1)
    # reader.SetReadAllScalars(1)
    # reader.SetReadAllTensors(1)
    # reader.SetReadAllVectors(1)

    reader.Update()
    mesh = reader.GetOutput()

    coord = vtk_to_numpy(mesh.GetPoints().GetData())
    cells = vtk_to_numpy(mesh.GetCells().GetData()).reshape(-1, 4)[:, 1:]
    point_nvecs = compute_point_normals(coord, cells)

    press = np.ascontiguousarray(
        vtk_to_numpy(mesh.GetPointData().GetAbstractArray('Pressure'))).astype(
            np.double)

    # TODO raine ERROR, now we need config_dict anyway
    if config_dict is not None:
        press = dimensionalize_pressure(press, config_dict)

    force = point_nvecs * press[:, None]

    #unit_norm = point_nvecs / np.linalg.norm(point_nvecs, axis=1, keepdims=True) # had to chage that with the last version of numpy
    unit_norm = point_nvecs / np.linalg.norm(point_nvecs)

    for name, values in iteritems({'n': unit_norm, 'f': force}):
        vectors = numpy_to_vtk(np.ascontiguousarray(values).astype(np.double),
                               deep=True,
                               array_type=vtk.VTK_FLOAT)
        vectors.SetName(name)
        mesh.GetPointData().AddArray(vectors)
        mesh.GetPointData().SetActiveVectors(name)

    # Write CSV force file
    ids = range(len(coord))

    su2_mesh_path = config_dict.get('MESH_FILENAME')

    marker_dict = get_mesh_markers_ids(su2_mesh_path)
    mesh_maker = []

    # Find which marker corespond to which ids
    for i in range(len(coord)):
        id_to_test = ids[i]

        find = False
        for marker, ids_list in marker_dict.items():
            if not find:
                if id_to_test in ids_list:
                    mesh_maker.append(marker)
                    find = True

    df = pandas.DataFrame(
        data={
            "ids": ids,
            'x': coord[:, 0],
            'y': coord[:, 1],
            'z': coord[:, 2],
            'fx': force[:, 0],
            'fy': force[:, 1],
            'fz': force[:, 2],
            'marker': mesh_maker
        })

    df.to_csv(force_file_path, sep=',', index=False)

    return mesh
Beispiel #60
0
def read_VTK(basefile,stratafile,initTime):
    '''
    This function reads strataform basement and stratigraphic VTK files and
    return numpy arrays for:
        - x, y, z coordinates
        - ages
        - mean grain size
    '''

    if os.path.isfile(basefile) and os.access(basefile, os.R_OK):
        print "Basement file exists and is readable"
    else:
        print "Either basement file is missing or is not readable"
        return


    if os.path.isfile(stratafile) and os.access(stratafile, os.R_OK):
        print "Stratigraphic file exists and is readable"
    else:
        print "Either stratigraphic file is missing or is not readable"
        return

    # Load basement surface vtk file as input
    Breader = vtkXMLUnstructuredGridReader()
    Breader.SetFileName(basefile)
    Breader.Update()

    # Get the coordinates of basement surface nodes
    bnodes_vtk_array= Breader.GetOutput().GetPoints().GetData()

    # Get the coordinates of the nodes and their mean grain sizes and ages
    bnodes_nummpy_array = vtk_to_numpy(bnodes_vtk_array)
    bx,by,bz= bnodes_nummpy_array[:,0],bnodes_nummpy_array[:,1],bnodes_nummpy_array[:,2]
    minBase = bz.min()

    dx = bx[1]-bx[0]
    nx = int((bx.max()-bx.min())/dx)+1
    ny = int((by.max()-by.min())/dx)+1

    baseX,baseY,baseZ = bx[nx*ny:],by[nx*ny:],bz[nx*ny:]
    bmgz = np.zeros(len(baseX))
    bage = np.zeros(len(baseX))
    bage.fill(initTime)

    # Load stratigraphic layer vtk file as input
    Sreader = vtk.vtkXMLUnstructuredGridReader()
    Sreader.SetFileName(stratafile)
    Sreader.Update()

    # Get the coordinates of nodes in the mesh
    snodes_vtk_array= Sreader.GetOutput().GetPoints().GetData()
    mgz_vtk = Sreader.GetOutput().GetPointData().GetArray("mean grain size")
    age_vtk = Sreader.GetOutput().GetPointData().GetArray("age smooth")

    # Get the coordinates of the nodes and their mean grain sizes and ages
    snodes_nummpy_array = vtk_to_numpy(snodes_vtk_array)
    sx,sy,sz = snodes_nummpy_array[:,0],snodes_nummpy_array[:,1],snodes_nummpy_array[:,2]

    mgz_numpy_array = vtk_to_numpy(mgz_vtk)
    smgz = mgz_numpy_array*1000. # change from m to mm

    age_numpy_array = vtk_to_numpy(age_vtk)
    sage = age_numpy_array

    # Concatenate basement and stratigraphy arrays
    x = np.hstack((baseX, sx))
    y = np.hstack((baseY, sy))
    z = np.hstack((baseZ, sz))
    mgz = np.hstack((bmgz, smgz))
    age = np.hstack((bage, sage))

    print "Numpy arrays with relevant informations have been created."

    return minBase, x, y, z, mgz, age