Beispiel #1
1
def plot_to_grid(grid_parameters, primary_variables, secondary_variables, number):


    # Get the shape from the grid parameters
    point_x = grid_parameters[0]
    point_y = grid_parameters[1]
    point_z = grid_parameters[2]
    nv, nu, nw = point_x.shape

    # "Unpack" the primary flow variables
    ro = primary_variables[0]
    ro_vel_x = primary_variables[1]
    ro_vel_y = primary_variables[2]
    ro_energy = primary_variables[3]

    # "Unpack" the existing secondary flow variables
    vel_x = secondary_variables[0]
    vel_y = secondary_variables[1]
    pressure = secondary_variables[2]
    enthalpy_stag = secondary_variables[3]

    # mach number
    velocity_magnitude = np.zeros((nv, nu, nw))
    for j in range(0, nv):
        for i in range(0, nu):
            velocity_magnitude[j,i,0] = np.sqrt( vel_x[j,i,0] * vel_x[j,i,0] + vel_y[j,i,0] * vel_y[j,i,0] )

    filename = "./output"+str(number)
    gridToVTK(filename, point_x, point_y, point_z, pointData={"pressure": pressure, "density": ro, "vel-x": vel_x, "vel-y": vel_y , "vel-mag": velocity_magnitude})
Beispiel #2
0
    def rcut2vtk(self, fname, data, r, name):
        """
        This routine transforms a radial cut of dimension (n_phi,n_theta)
        into a vts file.

        :param fname: file name
        :type fname: str
        :param data: input data
        :type data: numpy.ndarray
        :param r: radius of the selected cut
        :type r: float
        :param name: name of the physical field stored in the vts file
        :type name: str
        """
        data = symmetrize(data, self.minc)
        phi = np.linspace(0., 2.*np.pi, data.shape[0])
        X = np.zeros((data.shape[0], data.shape[1], 1), dtype=np.float32)
        Y = np.zeros_like(X)
        Z = np.zeros_like(X)
        ttheta, pphi = np.meshgrid(self.theta, phi)
        X[:, :, 0] = r*np.sin(ttheta)*np.cos(pphi)
        Y[:, :, 0] = r*np.sin(ttheta)*np.sin(pphi)
        Z[:, :, 0] = r*np.cos(ttheta)

        dat = np.zeros_like(X)
        point_data = {}
        dat[..., 0] = data
        point_data[name] = dat

        gridToVTK(fname, X, Y, Z, pointData=point_data)
        print('Store {}.vts'.format(fname))
Beispiel #3
0
 def export_to_vtk(self, vtk_filename="geo_grid", real_coords = True, **kwds):
     """Export grid to VTK for visualisation
     
     **Arguments**:
         - *vtk_filename* = string : vtk filename (obviously...)
         - *real_coords* = bool : model extent in "real world" coordinates
         
     **Optional Keywords**:
         - *grid* = numpy grid : grid to save to vtk (default: self.grid)
         - *var_name* = string : name of variable to plot (default: Geology)
     
     Note: requires pyevtk, available at: https://bitbucket.org/pauloh/pyevtk
     """
     grid = kwds.get("grid", self.grid)
     var_name = kwds.get("var_name", "Geology")
     from evtk.hl import gridToVTK
     # define coordinates
     x = np.zeros(self.nx + 1)
     y = np.zeros(self.ny + 1)
     z = np.zeros(self.nz + 1)
     x[1:] = np.cumsum(self.delx)
     y[1:] = np.cumsum(self.dely)
     z[1:] = np.cumsum(self.delz)
     
     # plot in coordinates
     if real_coords:
         x += self.xmin
         y += self.ymin
         z += self.zmin
     
     
     gridToVTK(vtk_filename, x, y, z,
               cellData = {var_name: grid})
Beispiel #4
0
    def scal3D2vtk(self, fname, data, name):
        """
        This routine transforms a 3-D scalar field of dimension
        (n_phi,n_theta,n_r) into a vts file.

        :param fname: file name
        :type fname: str
        :param data: input data
        :type data: numpy.ndarray
        :param r: radius of the selected cut
        :type r: float
        :param name: name of the physical field stored in the vts file
        :type name: str
        """
        data = symmetrize(data, self.minc)
        phi = np.linspace(0., 2.*np.pi, data.shape[0])
        X = np.zeros(data.shape, dtype=np.float32)
        Y = np.zeros_like(X)
        Z = np.zeros_like(X)
        ttheta, pphi, rr = np.meshgrid(self.theta, phi, self.radius)
        X = rr*np.sin(ttheta)*np.cos(pphi)
        Y = rr*np.sin(ttheta)*np.sin(pphi)
        Z = rr*np.cos(ttheta)*np.ones_like(pphi)

        point_data = {}
        point_data[name] = data

        gridToVTK(fname, X, Y, Z, pointData=point_data)
        print('Store {}.vts'.format(fname))
Beispiel #5
0
def plotvtk(x,y,name,fields):
    """ Dump solution to a VTK after flipping it. """
    z = array([0.0])
    Nx = len(x)
    Ny = len(y)
    transform = {k : flipud(v.T).reshape(Ny,Nx,1) for k,v in fields.items()}
    gridToVTK("./{}".format(name), x, y, z, pointData = transform)
Beispiel #6
0
    def mer2vtk(self, fname, data, phi0, name):
        """
        This routine transforms a meridional cut of dimension (n_theta,n_r)
        into a vts file.

        :param fname: file name
        :type fname: str
        :param data: input data
        :type data: numpy.ndarray
        :param phi0: longitude of the selected cut
        :type phi0: float
        :param name: name of the physical field stored in the vts file
        :type name: str
        """
        X = np.zeros((1, data.shape[0], data.shape[1]), dtype=np.float32)
        Y = np.zeros_like(X)
        Z = np.zeros_like(X)
        rr, ttheta = np.meshgrid(self.radius, self.theta)

        X[0, :, :] = rr*np.sin(ttheta)*np.cos(phi0)
        Y[0, :, :] = rr*np.sin(ttheta)*np.sin(phi0)
        Z[0, :, :] = rr*np.cos(ttheta)

        dat = np.zeros_like(X)
        dat[0, ...] = data

        point_data = {}
        point_data[name] = dat

        gridToVTK(fname, X, Y, Z, pointData=point_data)
        print('Store {}.vts'.format(fname))
Beispiel #7
0
def NParray2VTK(npmodel,dims,scale,vtkfilename):
    # Dimensions  
    # x, y & z Number of Voxels
    nx, ny, nz = dims[0], dims[1], dims[2]
    # x, y & z Length  
    lx , ly, lz = scale, scale, scale
    # x, y & z Voxel size 
    dx, dy, dz = lx/nx, ly/ny, lz/nz   # all equal
    # Coordinates - change to real pos later?
    # +0.1*dx used to get end value in arange 
    X = np.arange(0,lx+0.1*dx,dx, dtype='float64')  
    Y = np.arange(0,ly+0.1*dy,dy, dtype='float64')
    Z = np.arange(0,lz+0.1*dz,dz, dtype='float64')
    # x, y & z empty arrays
    x = np.zeros((nx + 1, ny + 1, nz + 1)) 
    y = np.zeros((nx + 1, ny + 1, nz + 1))
    z = np.zeros((nx + 1, ny + 1, nz + 1))  
    # Loop to fill position arrays
    for k in range(nz + 1): 
        for j in range(ny + 1):
            for i in range(nx + 1): 
                x[i,j,k] = X[i]  
                y[i,j,k] = Y[j] 
                z[i,j,k] = Z[k] 
    # write to VTK file
    vtkfilename = "./%s" % vtkfilename
    gridToVTK(vtkfilename, x, y, z, cellData = {vtkfilename : npmodel.astype(int)})  
Beispiel #8
0
    def write_cov_vtk_file(self,
                           cov_vtk_fn,
                           model_fn=None,
                           grid_east=None,
                           grid_north=None,
                           grid_z=None):
        """
        write a vtk file of the covariance to match things up
        """

        if model_fn is not None:
            m_obj = Model()
            m_obj.read_model_file(model_fn)
            grid_east = m_obj.grid_east
            grid_north = m_obj.grid_north
            grid_z = m_obj.grid_z

        if grid_east is not None:
            grid_east = grid_east
        if grid_north is not None:
            grid_north = grid_north
        if grid_z is not None:
            grid_z = grid_z

        # use cellData, this makes the grid properly as grid is n+1
        gridToVTK(cov_vtk_fn,
                  grid_north / 1000.,
                  grid_east / 1000.,
                  grid_z / 1000.,
                  cellData={'covariance_mask': self.mask_arr})

        self._logger.info('Wrote covariance file to {0}\n'.format(cov_vtk_fn))
Beispiel #9
0
def save_eostab_to_vtk(eosmat, filename):
    for view in ['DT']:
        for spec in ['e', 'i', 't']:
            pattern  = '_'.join([spec,view])
            ftables = [el for el in  eosmat.tables if pattern in el]
            if len(ftables):
                xl = []
                yl = []
                data = {}
                for tab_name in ftables:
                    tab = getattr(eosmat, tab_name)
                    xl.append(tab['R_Array'])
                    yl.append(tab['T_Array'])
                    data[tab_name] = _3d_reshape(tab['F_Array'])
                for x in xl:
                    assert_allclose(x,xl[0])
                for y in xl:
                    assert_allclose(y,xl[0])
                X, Y = np.meshgrid(x,y, indexing='ij')
                X = _3d_reshape(X)
                Y = _3d_reshape(Y)
                Z = np.zeros(X.shape)

                #print X
                gridToVTK("./{0}".format(filename), X, Y, Z, pointData=data)
def NParray2VTK(npmodel, dims, scale, vtkfilename):
    # Dimensions
    # x, y & z Number of Voxels
    nx, ny, nz = dims, dims, dims
    # x, y & z Length
    lx, ly, lz = scale, scale, scale
    # x, y & z Voxel size
    dx, dy, dz = lx / nx, ly / ny, lz / nz  # all equal
    # Coordinates - change to real pos later?
    # +0.1*dx used to get end value in arange
    X = np.arange(0, lx + 0.1 * dx, dx, dtype='float64')
    Y = np.arange(0, ly + 0.1 * dy, dy, dtype='float64')
    Z = np.arange(0, lz + 0.1 * dz, dz, dtype='float64')
    # x, y & z empty arrays
    x = np.zeros((nx + 1, ny + 1, nz + 1))
    y = np.zeros((nx + 1, ny + 1, nz + 1))
    z = np.zeros((nx + 1, ny + 1, nz + 1))
    # Loop to fill position arrays
    for k in range(nz + 1):
        for j in range(ny + 1):
            for i in range(nx + 1):
                x[i, j, k] = X[i]
                y[i, j, k] = Y[j]
                z[i, j, k] = Z[k]
    # write to VTK file
    vtkfilename = "./%s" % vtkfilename
    gridToVTK(vtkfilename,
              x,
              y,
              z,
              cellData={vtkfilename: npmodel.astype(int)})
Beispiel #11
0
def save_eostab_to_vtk(eosmat, filename):
    for view in ['DT']:
        for spec in ['e', 'i', 't']:
            pattern = '_'.join([spec, view])
            ftables = [el for el in eosmat.tables if pattern in el]
            if len(ftables):
                xl = []
                yl = []
                data = {}
                for tab_name in ftables:
                    tab = getattr(eosmat, tab_name)
                    xl.append(tab['R_Array'])
                    yl.append(tab['T_Array'])
                    data[tab_name] = _3d_reshape(tab['F_Array'])
                for x in xl:
                    assert_allclose(x, xl[0])
                for y in xl:
                    assert_allclose(y, xl[0])
                X, Y = np.meshgrid(x, y, indexing='ij')
                X = _3d_reshape(X)
                Y = _3d_reshape(Y)
                Z = np.zeros(X.shape)

                #print X
                gridToVTK("./{0}".format(filename), X, Y, Z, pointData=data)
Beispiel #12
0
    def equat2vtk(self, fname, data, name):
        """
        This routine transforms an equatorial cut of dimension (n_phi,n_r)
        into a vts file.

        :param fname: file name
        :type fname: str
        :param data: input data
        :type data: numpy.ndarray
        :param name: name of the physical field stored in the vts file
        :type name: str
        """
        data = symmetrize(data, self.minc)
        phi = np.linspace(0., 2.*np.pi, data.shape[0])
        X = np.zeros((1, data.shape[0], data.shape[1]), dtype=np.float32)
        Y = np.zeros_like(X)
        Z = np.zeros_like(X)
        rr, pphi = np.meshgrid(self.radius, phi)
        X[0, :, :] = rr*np.cos(pphi)
        Y[0, :, :] = rr*np.sin(pphi)

        dat = np.zeros_like(X)
        dat[0, ...] = data

        point_data = {}
        point_data[name] = dat

        gridToVTK(fname, X, Y, Z, pointData=point_data)
        print('Store {}.vts'.format(fname))
Beispiel #13
0
 def export_to_vtk(self, **kwds):
     """Export model to VTK
     
     Export the geology blocks to VTK for visualisation of the entire 3-D model in an
     external VTK viewer, e.g. Paraview.
     
     ..Note:: Requires pyevtk, available for free on: https://github.com/firedrakeproject/firedrake/tree/master/python/evtk
     
     **Optional keywords**:
         - *vtk_filename* = string : filename of VTK file (default: output_name)
         - *data* = np.array : data array to export to VKT (default: entire block model)
     """
     vtk_filename = kwds.get("vtk_filename", self.basename)
     
     from evtk.hl import gridToVTK
     # Coordinates
     x = np.arange(0, self.extent_x + 0.1*self.delx, self.delx, dtype='float64')
     y = np.arange(0, self.extent_y + 0.1*self.dely, self.dely, dtype='float64')
     z = np.arange(0, self.extent_z + 0.1*self.delz, self.delz, dtype='float64')
     
     # self.block = np.swapaxes(self.block, 0, 2)
     
     if kwds.has_key("data"):
         gridToVTK(vtk_filename, x, y, z, cellData = {"data" : kwds['data']})         
     else:
         gridToVTK(vtk_filename, x, y, z, cellData = {"geology" : self.block})         
Beispiel #14
0
    def export_to_vtk(self, grid, name, **kwds):
        """Export model to VTK
        
        Export grid to VTK for visualisation of the entire 3-D model in an
        external VTK viewer, e.g. Paraview.
        
        ..Note:: Requires pyevtk, available for free on: https://github.com/firedrakeproject/firedrake/tree/master/python/evtk
        
        """
        vtk_filename = "GBasin_%s" % name

        from evtk.hl import gridToVTK
        # Coordinates, from one output file
        NO_tmp = self.load_output_file(0)

        x = np.arange(0,
                      NO_tmp.extent_x + 0.1 * NO_tmp.delx,
                      NO_tmp.delx,
                      dtype='float64')
        y = np.arange(0,
                      NO_tmp.extent_y + 0.1 * NO_tmp.dely,
                      NO_tmp.dely,
                      dtype='float64')
        z = np.arange(0,
                      NO_tmp.extent_z + 0.1 * NO_tmp.delz,
                      NO_tmp.delz,
                      dtype='float64')

        # self.block = np.swapaxes(self.block, 0, 2)

        gridToVTK(vtk_filename, x, y, z, cellData={"%s" % name: grid})
Beispiel #15
0
def opg_op2vtk(data, fname):
    x = data['dens'][:]
    y = data['temp'][:]
    z = 0.5 * (data['groups'][1:] + data['groups'][:-1])
    #X, Y, Z = meshgrid_nd(x, y,z)
    pointData = {key: data[key][:] for key in ['opp_mg', 'opr_mg', 'emp_mg']}

    gridToVTK(fname, x, y, z, pointData=pointData)
Beispiel #16
0
def opg_op2vtk(data, fname):
    x = data['dens'][:]
    y = data['temp'][:]
    z = 0.5*(data['groups'][1:] + data['groups'][:-1])
    #X, Y, Z = meshgrid_nd(x, y,z)
    pointData = {key: data[key][:] for key in ['opp_mg', 'opr_mg', 'emp_mg']}

    gridToVTK(fname, x, y, z, pointData = pointData)
Beispiel #17
0
def arrayToVTKfile(vtkfilename,array,dims,scale,translate,voxelsize):
#def main(binvoxfile):
    # OPEN BINVOX FILE AS NP ARRAY
    
    
    # buffer 3d array
    #olddims = tempmodel.dims # old dims before buffer
    #oldscale = tempmodel.scale  # old scale before buffer
    #oldtranslate = tempmodel.translate # old translate before buffer
    #voxelsize = oldscale/olddims[0]
    #print "voxelsize = %s "  % (voxelsize)
    # BUFFER THE ARRAY 
    #model = np.zeros( (olddims[0]+2,olddims[1]+2,olddims[2]+2))    
    #model[1:olddims[0]+1,1:olddims[1]+1,1:olddims[2]+1]=tempmodel.data
    #dims = [x+2 for x in olddims]
    #print dims
    #scale = oldscale + 2*voxelsize
    #translate = [x-voxelsize for x in oldtranslate]
    
    # WRITE TO VTK 
    
    #dims = dims[0]
    #vtkfilename = binvoxfile.replace(".binvox","")
    # Dimensions  
    # x, y & z Number of Voxels
    nx, ny, nz = dims,dims,dims
    # x, y & z Length  
    lx , ly, lz = scale,scale,scale
    # x, y & z Voxel size 
    dx, dy, dz = lx/nx, ly/ny, lz/nz   # all equal
    # Coordinates - change to real pos later?
    # +0.1*dx used to get end value in arange 
    X = np.arange(0,lx+0.1*dx,dx, dtype='float64')  
    Y = np.arange(0,ly+0.1*dy,dy, dtype='float64')
    Z = np.arange(0,lz+0.1*dz,dz, dtype='float64')
    # x, y & z empty arrays
    x = np.zeros((nx + 1, ny + 1, nz + 1)) 
    y = np.zeros((nx + 1, ny + 1, nz + 1))
    z = np.zeros((nx + 1, ny + 1, nz + 1))  
    # Loop to fill position arrays
    for k in range(nz + 1): 
        for j in range(ny + 1):
            for i in range(nx + 1): 
                x[i,j,k] = X[i]  
                y[i,j,k] = Y[j] 
                z[i,j,k] = Z[k] 
    # write to VTK file
    vtkfilename = "./%s" % vtkfilename
    gridToVTK(vtkfilename, x, y, z, cellData = {vtkfilename : array.astype(int)})

    
#if __name__ == "__main__":
    #main("testGeom_64.binvox")    
    #main("montreal131.binvox")
Beispiel #18
0
def model2vtkgrid(ModEMmodelfn,VTKfn='VTKresistivitymodel' ):
    """
    Convert ModEM output files (model and responses) into 3D VTK resistivity grid

    Input:
    - ModEM model name
    - [optional] VTK resistivity grid file - output file name
    """

    if not os.path.isfile(os.path.abspath(os.path.realpath(ModEMmodelfn))):
        sys.exit('ERROR - could not find file:\n%s'%(os.path.abspath(os.path.realpath(ModEMmodelfn))))

    if not os.path.isfile(os.path.abspath(os.path.realpath(VTKfn))):
        VTKfn = os.path.abspath(os.path.realpath('VTKresistivitymodel'))



    F = open(ModEMmodelfn, 'r')
    raw_data = F.readlines()
    F.close()

    coords_list = mdt.getmeshblockcoordinates(ModEMmodelfn)
    n_north_blocks = len(coords_list[0])
    n_east_blocks  = len(coords_list[1])
    n_depth_blocks = len(coords_list[2])

    res_model = np.zeros((n_north_blocks,n_east_blocks,n_depth_blocks))


    current_line_idx = 5
    for idx_depth in range(n_depth_blocks):
        #catering for the empty line between depths
        current_line_idx += 1
        for idx_east in range(n_east_blocks):
            #use North-to-South convention in the grid!!
            current_line = raw_data[current_line_idx]
            lo_data_tmp = current_line.strip().split()
            for idx_north in range(n_north_blocks):
                res_model[idx_north,idx_east, idx_depth] = np.exp(float(lo_data_tmp[idx_east]) )
            current_line_idx +=1

    #transfer grid to km  instead of m
    #use North-to-South convention in the grid!!
    coords_list[0].reverse()
    N = np.array(coords_list[0])/1000.
    E = np.array(coords_list[1])/1000.
    D = np.array(coords_list[2])/1000.


    gridToVTK(VTKfn, N, E, D, cellData = {'resistivity (in Ohm)' : res_model})

    print('Created Resistivity File: ',VTKfn)

    return VTKfn
Beispiel #19
0
 def writeAllToParaview(self,start=0,end=100000,skip=1):
   grid = np.load('../DGgrid.npz')
   x,y,z = np.meshgrid(grid['x'],grid['y'],grid['z'],indexing='ij')
   for i in range(0,end,skip):
     sol_str = 'npsol' + str(i) + '.npz'
     if (os.path.isfile(sol_str)):
       print('found ' + sol_str)
       sol = np.load('npsol' + str(i) + '.npz')
       string = 'PVsol' + str(i)
       gridToVTK(string, x,y,z, pointData = {"rho" : sol['U'][0] , \
         "u" : sol['U'][1]/sol['U'][0] , "v" : sol['U'][2], "w" : sol['U'][3]/sol['U'][0], \
         "rhoE" : sol['U'][4]} )
Beispiel #20
0
def model2vtkgrid(ModEMmodelfn, VTKfn='VTKresistivitymodel'):
    """
    Convert ModEM output files (model and responses) into 3D VTK resistivity grid

    Input:
    - ModEM model name
    - [optional] VTK resistivity grid file - output file name
    """

    if not os.path.isfile(os.path.abspath(os.path.realpath(ModEMmodelfn))):
        sys.exit('ERROR - could not find file:\n%s' %
                 (os.path.abspath(os.path.realpath(ModEMmodelfn))))

    if not os.path.isfile(os.path.abspath(os.path.realpath(VTKfn))):
        VTKfn = os.path.abspath(os.path.realpath('VTKresistivitymodel'))

    F = open(ModEMmodelfn, 'r')
    raw_data = F.readlines()
    F.close()

    coords_list = mdt.getmeshblockcoordinates(ModEMmodelfn)
    n_north_blocks = len(coords_list[0])
    n_east_blocks = len(coords_list[1])
    n_depth_blocks = len(coords_list[2])

    res_model = np.zeros((n_north_blocks, n_east_blocks, n_depth_blocks))

    current_line_idx = 5
    for idx_depth in range(n_depth_blocks):
        # catering for the empty line between depths
        current_line_idx += 1
        for idx_east in range(n_east_blocks):
            # use North-to-South convention in the grid!!
            current_line = raw_data[current_line_idx]
            lo_data_tmp = current_line.strip().split()
            for idx_north in range(n_north_blocks):
                res_model[idx_north, idx_east,
                          idx_depth] = np.exp(float(lo_data_tmp[idx_east]))
            current_line_idx += 1

    # transfer grid to km  instead of m
    # use North-to-South convention in the grid!!
    coords_list[0].reverse()
    N = np.array(coords_list[0]) / 1000.
    E = np.array(coords_list[1]) / 1000.
    D = np.array(coords_list[2]) / 1000.

    gridToVTK(VTKfn, N, E, D, cellData={'resistivity (in Ohm)': res_model})

    print 'Created Resistivity File: ', VTKfn

    return VTKfn
Beispiel #21
0
def saveVTK(filename, i, j):
    ind = numpy.arange(0, len(i)*len(j), dtype = 'uint32')
    temp = numpy.zeros((1), dtype = 'int32')

    def fun(x,y):
        array = numpy.zeros((len(x),len(y)))
        for i in range(len(x)):
            array[i, :] = x[i]*y

        return array

    dictionary = {'whatever': fun(i,j)[:,None]}
    evtk.gridToVTK(filename, i, j, temp, pointData = dictionary)
Beispiel #22
0
    def export_vtk_rectilinear(geo_data, block, path=None):
        """
        Export data to a vtk file for posterior visualizations
        Args:
            geo_data(gempy.InputData): All values of a DataManagement object
            block(numpy.array): 3D array containing the lithology block
            path (str): path to the location of the vtk

        Returns:
            None
        """

        from evtk.hl import gridToVTK

        import numpy as np

        import random as rnd

        # Dimensions

        nx, ny, nz = geo_data.resolution

        lx = geo_data.extent[0] - geo_data.extent[1]
        ly = geo_data.extent[2] - geo_data.extent[3]
        lz = geo_data.extent[4] - geo_data.extent[5]

        dx, dy, dz = lx / nx, ly / ny, lz / nz

        ncells = nx * ny * nz

        npoints = (nx + 1) * (ny + 1) * (nz + 1)

        # Coordinates
        x = np.arange(0, lx + 0.1 * dx, dx, dtype='float64')

        y = np.arange(0, ly + 0.1 * dy, dy, dtype='float64')

        z = np.arange(0, lz + 0.1 * dz, dz, dtype='float64')

        # Variables

        lith = block.reshape((nx, ny, nz))
        if not path:
            path = "./Lithology_block"

        gridToVTK(path, x, y, z, cellData={"Lithology": lith})
Beispiel #23
0
    def write_vtk(s):
        from evtk.hl import gridToVTK

        xgrid = np.outer(np.sin(np.radians(s.thetaphi)) * np.cos(np.radians(s.phitheta)), s.radii)
        ygrid = np.outer(np.sin(np.radians(s.thetaphi)) * np.sin(np.radians(s.phitheta)), s.radii)
        zgrid = np.outer(np.cos(np.radians(s.thetaphi)), s.radii)

        xgrid = xgrid.reshape(s.ntheta, s.nphi, s.nr)
        ygrid = ygrid.reshape(s.ntheta, s.nphi, s.nr)
        zgrid = zgrid.reshape(s.ntheta, s.nphi, s.nr)

        print s.kernel[5].shape
        print xgrid.shape
        print ygrid.shape
        print zgrid.shape

        gridToVTK('kernel', xgrid, ygrid, zgrid, pointData={'kernel':s.kernel[8,:,:,:]})
Beispiel #24
0
def toVtr(filePrefix):

    iFile = filePrefix + '.nc'

    # geometry
    rho = read_data(iFile, 'rho')
    nx, ny, nz = rho.shape
    lx, ly, lz = 1.0 * nx, 1.0 * ny, 1.0 * nz
    dx, dy, dz = lx / nx, ly / ny, lz / nz
    ncells = nx * ny * nz

    # Coordinates
    x = np.arange(0, lx + 0.1 * dx, dx, dtype='float64')
    y = np.arange(0, ly + 0.1 * dy, dy, dtype='float64')
    z = np.arange(0, lz + 0.1 * dz, dz, dtype='float64')

    # read input data
    rho = read_data(iFile, 'rho')
    rho_vx = read_data(iFile, 'rho_vx')
    rho_vy = read_data(iFile, 'rho_vy')
    rho_vz = read_data(iFile, 'rho_vz')
    Bx = read_data(iFile, 'Bx')
    By = read_data(iFile, 'By')
    Bz = read_data(iFile, 'Bz')
    E = read_data(iFile, 'E')

    #
    # write output file
    #

    # write file
    gridToVTK(filePrefix,
              x,
              y,
              z,
              cellData={
                  "rho": rho,
                  "E": E,
                  "rho_vx": rho_vx,
                  "rho_vy": rho_vy,
                  "rho_vz": rho_vz,
                  "Bx": Bx,
                  "By": By,
                  "Bz": Bz
              })
Beispiel #25
0
    def _write_network(points_array, multiple_networks=False):
        n_columns = int(points_array.shape[0])
        n_rows = int(points_array.shape[1])

        X = np.zeros((n_rows, n_columns, 1))
        Y = np.zeros((n_rows, n_columns, 1))
        Z = np.zeros((n_rows, n_columns, 1))

        for i in range(n_columns):
            for j in range(n_rows):
                X[j, i, 0] = points_array[i, j, 0]
                Y[j, i, 0] = points_array[i, j, 1]
                Z[j, i, 0] = points_array[i, j, 2]

        if multiple_networks:
            gridToVTK(filename + '_network' + str(n + 1), X, Y, Z)
        else:
            gridToVTK(filename + '_network', X, Y, Z)
Beispiel #26
0
def grid2vtk():
    fd = FldFolder()
    vtkfolder= 'vtk'

    from evtk.hl import gridToVTK
    grid = fd.get_grid()
    x = grid['x']
    y = grid['y']

    nx,ny,nz,ne = x.shape


    x = grid_to_3d(x)[:,0,0]
    y = grid_to_3d(y)[0,:,0]
    z = np.array([0.0])

    dat = fd('2000')['data']
    dat ={key:grid_to_3d( dat[ key ]  ) for key in  dat}

    gridToVTK('./vtk/test',x,y,z,pointData = dat)
Beispiel #27
0
def plot_to_grid(grid_parameters, primary_variables, secondary_variables,
                 number):

    # Get the shape from the grid parameters
    point_x = grid_parameters[0]
    point_y = grid_parameters[1]
    point_z = grid_parameters[2]
    nv, nu, nw = point_x.shape

    # "Unpack" the primary flow variables
    ro = primary_variables[0]
    ro_vel_x = primary_variables[1]
    ro_vel_y = primary_variables[2]
    ro_energy = primary_variables[3]

    # "Unpack" the existing secondary flow variables
    vel_x = secondary_variables[0]
    vel_y = secondary_variables[1]
    pressure = secondary_variables[2]
    enthalpy_stag = secondary_variables[3]

    # mach number
    velocity_magnitude = np.zeros((nv, nu, nw))
    for j in range(0, nv):
        for i in range(0, nu):
            velocity_magnitude[j, i,
                               0] = np.sqrt(vel_x[j, i, 0] * vel_x[j, i, 0] +
                                            vel_y[j, i, 0] * vel_y[j, i, 0])

    filename = "./output" + str(number)
    gridToVTK(filename,
              point_x,
              point_y,
              point_z,
              pointData={
                  "pressure": pressure,
                  "density": ro,
                  "vel-x": vel_x,
                  "vel-y": vel_y,
                  "vel-mag": velocity_magnitude
              })
Beispiel #28
0
def export_vtk_rectilinear(geo_data, block_lith, path=None):
    """
        export vtk
        :return:
        """

    from evtk.hl import gridToVTK

    import numpy as np

    import random as rnd

    # Dimensions

    nx, ny, nz = geo_data.resolution

    lx = geo_data.extent[0] - geo_data.extent[1]
    ly = geo_data.extent[2] - geo_data.extent[3]
    lz = geo_data.extent[4] - geo_data.extent[5]

    dx, dy, dz = lx / nx, ly / ny, lz / nz

    ncells = nx * ny * nz

    npoints = (nx + 1) * (ny + 1) * (nz + 1)

    # Coordinates
    x = np.arange(0, lx + 0.1 * dx, dx, dtype='float64')

    y = np.arange(0, ly + 0.1 * dy, dy, dtype='float64')

    z = np.arange(0, lz + 0.1 * dz, dz, dtype='float64')

    # Variables

    lith = block_lith.reshape((nx, ny, nz))
    if not path:
        path = "./Lithology_block"

    gridToVTK(path, x, y, z, cellData={"Lithology": lith})
def toVtr(filePrefix):

    iFile=filePrefix+'.nc'

    # geometry
    rho        = read_data(iFile, 'rho')
    nx,ny,nz   = rho.shape
    lx, ly, lz = 1.0*nx, 1.0*ny, 1.0*nz
    dx, dy, dz = lx/nx, ly/ny, lz/nz
    ncells     = nx * ny * nz

    # Coordinates
    x = np.arange(0, lx + 0.1*dx, dx, dtype='float64')
    y = np.arange(0, ly + 0.1*dy, dy, dtype='float64')
    z = np.arange(0, lz + 0.1*dz, dz, dtype='float64')

    # read input data
    rho    = read_data(iFile, 'rho')
    rho_vx = read_data(iFile, 'rho_vx')
    rho_vy = read_data(iFile, 'rho_vy')
    rho_vz = read_data(iFile, 'rho_vz')
    Bx     = read_data(iFile, 'Bx')
    By     = read_data(iFile, 'By')
    Bz     = read_data(iFile, 'Bz')
    E      = read_data(iFile, 'E')

    #
    # write output file
    #
    
    # write file
    gridToVTK(filePrefix, x, y, z, cellData = {"rho" : rho,
                                               "E" : E,
                                               "rho_vx" : rho_vx,
                                               "rho_vy" : rho_vy,
                                               "rho_vz" : rho_vz,
                                               "Bx" : Bx,
                                               "By" : By,
                                               "Bz" : Bz})
Beispiel #30
0
 def export_to_vtk(self, **kwds):
     """Export model to VTK
     
     Export the geology blocks to VTK for visualisation of the entire 3-D model in an
     external VTK viewer, e.g. Paraview.
     
     ..Note:: Requires pyevtk, available for free on: https://github.com/firedrakeproject/firedrake/tree/master/python/evtk
     
     **Optional keywords**:
         - *vtk_filename* = string : filename of VTK file (default: output_name)
     """
     vtk_filename = kwds.get("vtk_filename", self.basename)
     
     from evtk.hl import gridToVTK
     # Coordinates
     x = np.arange(0, self.extent_x + 0.1*self.delx, self.delx, dtype='float64')
     y = np.arange(0, self.extent_y + 0.1*self.dely, self.dely, dtype='float64')
     z = np.arange(0, self.extent_z + 0.1*self.delz, self.delz, dtype='float64')
     
     # self.block = np.swapaxes(self.block, 0, 2)
     
     gridToVTK(vtk_filename, x, y, z, cellData = {"geology" : self.block})         
Beispiel #31
0
def generate_surface(data, filename='panair'):
    '''
    Function to generate vtk files from a panair input mesh
    INPUT :
    - data is a list of networks which are 3D arrays with the dimensions being
    columns, rows, and coordinates)
    - 'filename' is a string to use in filenames.
    For example 'panair' will result in files called 'panair_network_1', etc.

    OUTPUT :
    The function will produce one or several files, one for each network,
    in the folder it's run from.
    '''
    from evtk.hl import gridToVTK
    # TODO: Currently not working when meshes seeds are not the same

    # X, Y, Z = data
    X = np.ascontiguousarray(data[:, :, 0])
    Y = np.ascontiguousarray(data[:, :, 1])
    Z = np.ascontiguousarray(data[:, :, 2])
    gridToVTK(filename+'_network', X[:, :, None], Y[:, :, None], Z[:, :, None],
              cellData={'test': Z[:, :, None]})
Beispiel #32
0
 def export_to_vtk(self, grid, name, **kwds):
     """Export model to VTK
     
     Export grid to VTK for visualisation of the entire 3-D model in an
     external VTK viewer, e.g. Paraview.
     
     ..Note:: Requires pyevtk, available for free on: https://github.com/firedrakeproject/firedrake/tree/master/python/evtk
     
     """
     vtk_filename = "GBasin_%s" % name
     
     from evtk.hl import gridToVTK
     # Coordinates, from one output file
     NO_tmp = self.load_output_file(0)
     
     x = np.arange(0, NO_tmp.extent_x + 0.1*NO_tmp.delx, NO_tmp.delx, dtype='float64')
     y = np.arange(0, NO_tmp.extent_y + 0.1*NO_tmp.dely, NO_tmp.dely, dtype='float64')
     z = np.arange(0, NO_tmp.extent_z + 0.1*NO_tmp.delz, NO_tmp.delz, dtype='float64')
     
     # self.block = np.swapaxes(self.block, 0, 2)
     
     gridToVTK(vtk_filename, x, y, z, cellData = {"%s" % name : grid})         
Beispiel #33
0
    def saveToVTK(self, path: str):
        import evtk.hl as vtk_export

        x_coords = [node.x for node in self.__nodes[::self.__data.mH]]
        y_coords = [node.y for node in self.__nodes[:self.__data.mH:]]
        temp = [node.value for node in self.__nodes]

        x = np.zeros((self.__data.mW, self.__data.mH, 1))
        y = np.zeros((self.__data.mW, self.__data.mH, 1))
        z = np.zeros((self.__data.mW, self.__data.mH, 1))
        temp_matrix = np.asarray(temp).reshape(
            (self.__data.mW, self.__data.mH, 1))

        for j in range(self.__data.mW):
            for i in range(self.__data.mH):
                x[j, i, 0] = x_coords[j]
                y[j, i, 0] = y_coords[i]
                temp_matrix[j, i, 0] = temp[i + j * self.__data.mH]

        vtk_export.gridToVTK(path,
                             x,
                             y,
                             z,
                             pointData={"Temperature": temp_matrix})
Beispiel #34
0
zn = len(Zlist)

time = range(dayi,dayf,days)

t = 0

for tt in time:
 tlabel = str(tt)
 while len(tlabel) < 3: tlabel = '0'+tlabel
 #
 file1 = './vts/'+basename+'_'+label+'_' + tlabel
 print file1

 var = np.zeros((xn,yn,zn))
 x = np.zeros((xn,yn,zn))
 y = np.zeros((xn,yn,zn))
 z = np.zeros((xn,yn,zn))
 #
 Temp = fio.read_Scalar(path+'/'+basename+'_'+label+'_'+str(tt)+'.csv',xn,yn,zn)
 #
 for k in range(len(Zlist)):
  for i in range(len(Xlist)):
   for j in range(len(Ylist)):
    var[i,j,k] = Temp[i,j,k]
    x[i,j,k] = Xlist[i]
    y[i,j,k] = Ylist[j]
    z[i,j,k] = Zlist[k] 

 gridToVTK(file1, x,y,z, pointData = {basename : var})

Beispiel #35
0
def initial_setup(nu, nv, nw):
    #--------------------------------------------------------------
    #
    # Read in the boundary conditions file and save variables
    #
    #--------------------------------------------------------------

    # Read in boundary condition file!
    bcfile = open('boundary_conditions.txt', 'r')
    input_data = bcfile.readlines()
    bcfile.close()

    # Skip the header and proceed with the initialization!
    line_2 = input_data[1].split()
    rgas = np.float(line_2[2])

    line_3 = input_data[2].split()
    gamma = np.float(line_3[2])

    line_4 = input_data[3].split()
    pressure_stag_inlet = np.float(line_4[2])

    line_5 = input_data[4].split()
    temp_stag_inlet = np.float(line_5[2])

    line_6 = input_data[5].split()
    alpha_1 = np.float(line_6[2])

    line_7 = input_data[6].split()
    pressure_static_exit = np.float(line_7[2])

    line_8 = input_data[7].split()
    cfl = np.float(line_8[2])

    line_9 = input_data[8].split()
    smooth_fac_input = np.float(line_9[2])

    line_10 = input_data[9].split()
    nsteps = np.float(line_10[2])

    line_11 = input_data[10].split()
    conlim_in = np.float(line_11[2])

    boundary_conditions = [
        rgas, gamma, pressure_stag_inlet, temp_stag_inlet, alpha_1,
        pressure_static_exit, cfl, smooth_fac_input, nsteps, conlim_in
    ]

    #----------------------------------------------
    #
    # Setup other variables!
    #
    #----------------------------------------------
    cp = rgas * gamma / (gamma - 1.0)
    cv = cp / (gamma * 1.0)
    gamma_factor = (gamma - 1.0) / (gamma * 1.0)

    #----------------------------------------------
    #
    # Here we initialize the flow variables!
    #
    #-----------------------------------------------
    ro = np.zeros((nv, nu, nw))  # Density
    ro_vel_x = np.zeros((nv, nu, nw))  # Density * Velocity in "x" direction
    ro_vel_y = np.zeros((nv, nu, nw))  # Density * Velocity in "y" direction
    pressure = np.zeros((nv, nu, nw))  # static pressure
    ro_energy = np.zeros((nv, nu, nw))  # Density * energy
    vel_x = np.zeros((nv, nu, nw))  # velocity-x
    vel_y = np.zeros((nv, nu, nw))  # velocity-y
    enthalpy_stag = np.zeros((nv, nu, nw))  # Stagnation enthalpy

    #----------------------------------------------
    #
    # Here we initialize the fluxes!
    #
    #-----------------------------------------------
    flux_i_mass = np.zeros((nv, nu))  # Mass
    flux_j_mass = np.zeros((nv, nu))

    flux_i_xmom = np.zeros((nv, nu))  # X-MOMENTUM
    flux_j_xmom = np.zeros((nv, nu))

    flux_i_ymom = np.zeros((nv, nu))  # Y-MOMENTUM
    flux_j_ymom = np.zeros((nv, nu))

    flux_i_enthalpy = np.zeros((nv, nu))  # Enthalpy
    flux_j_enthalpy = np.zeros((nv, nu))

    flow = np.zeros((nu, 1))  # total mass flow rate across each "i"

    #----------------------------------------------
    #
    # new guess subroutine
    #
    #-----------------------------------------------
    jmid = nv / 2.0
    temp_static_exit = temp_stag_inlet * (pressure_static_exit /
                                          pressure_stag_inlet)**gamma_factor
    vel_exit = np.sqrt(2 * cp * (temp_stag_inlet - temp_static_exit))
    ro_exit = pressure_static_exit / rgas / temp_static_exit
    pressure_static_inlet = 55000
    temp_static_inlet = temp_stag_inlet * (pressure_static_inlet /
                                           pressure_stag_inlet)**gamma_factor
    vel_inlet = np.sqrt(2 * cp * (temp_stag_inlet - temp_static_inlet))
    ro_inlet = pressure_static_inlet / rgas / temp_static_inlet

    # Get the grid!
    grid_parameters = create_grid(nu, nv, nw)
    point_x = grid_parameters[0]
    point_y = grid_parameters[1]
    point_z = grid_parameters[2]

    # Initial guess!
    for j in range(0, nv):
        for i in range(0, nu):
            ro[j, i, 0] = 1.2
            ro_vel_x[j, i, 0] = 100 * (i * 1.0) / (nu * 1.0)
            ro_vel_y[j, i, 0] = 0.0
            pressure[j, i, 0] = 100000 * (0.9 + 0.1 * (i * 1.0) / (nu * 1.0))
            enthalpy_stag[j, i, 0] = 300000
            ro_energy[j, i, 0] = pressure[j, i, 0] / (gamma - 1.0)

    for j in range(0, nv):
        for i in range(0, nu - 1):
            dx = point_x[jmid, i + 1, 0] - point_x[jmid, i, 0]
            dy = point_y[jmid, i + 1, 0] - point_y[jmid, i, 0]
            ds = np.sqrt(dx * dx + dy * dy)

            vel_local = vel_inlet + (vel_exit - vel_inlet) * (1.0 * (i - 1.0) /
                                                              (nu - 1.0))
            ro_local = ro_inlet + (ro_exit - ro_inlet) * (1.0 * (i - 1.0) /
                                                          (nu - 1.0))
            temp_local = temp_static_inlet + (temp_static_exit -
                                              temp_static_inlet) * (1.0 *
                                                                    (i - 1.0) /
                                                                    (nu - 1.0))

            velx = vel_local * dx / ds
            vely = vel_local * dy / ds

            ro_vel_x[j, i, 0] = ro_local * velx
            ro_vel_y[j, i, 0] = ro_local * vely
            ro[j, i, 0] = ro_local
            ro_energy[j, i, 0] = ro_local * (cv * temp_local +
                                             0.5 * vel_local * vel_local)

        ro_vel_x[j, nu - 1, 0] = ro_vel_x[j, nu - 2, 0]
        ro_vel_y[j, nu - 1, 0] = ro_vel_y[j, nu - 2, 0]
        ro[j, nu - 1, 0] = ro[j, nu - 2, 0]
        ro_energy[j, nu - 1, 0] = ro_energy[j, nu - 2, 0]

    #-------------------------------------------------------------------------
    #
    # Output initial flow solution with grid
    #
    #-------------------------------------------------------------------------
    gridToVTK("./initial_flow",
              point_x,
              point_y,
              point_z,
              pointData={
                  "pressure": pressure,
                  "density": ro,
                  "density-velx": ro_vel_x
              })

    #-------------------------------------------------------------------------
    #
    # Setting primary & secondary flow variables
    #
    #-------------------------------------------------------------------------
    primary_variables = {}
    secondary_variables = {}
    primary_variables[0] = ro
    primary_variables[1] = ro_vel_x
    primary_variables[2] = ro_vel_y
    primary_variables[3] = ro_energy
    secondary_variables[0] = vel_x
    secondary_variables[1] = vel_y
    secondary_variables[2] = pressure
    secondary_variables[3] = enthalpy_stag

    #-------------------------------------------------------------------------
    #
    # Setting the fluxes
    #
    #-------------------------------------------------------------------------
    fluxes = {}
    fluxes[0] = flux_i_mass
    fluxes[1] = flux_j_mass
    fluxes[2] = flux_i_xmom
    fluxes[3] = flux_j_xmom
    fluxes[4] = flux_i_ymom
    fluxes[5] = flux_j_ymom
    fluxes[6] = flux_i_enthalpy
    fluxes[7] = flux_j_enthalpy
    fluxes[8] = flow

    secondary_variables = set_other_variables(primary_variables,
                                              secondary_variables,
                                              boundary_conditions,
                                              grid_parameters)

    return primary_variables, secondary_variables, fluxes, boundary_conditions, grid_parameters
Beispiel #36
0
lx, ly, lz = 1.0, 1.0, 1.0
dx, dy, dz = lx / nx, ly / ny, lz / nz

ncells = nx * ny * nz
npoints = (nx + 1) * (ny + 1) * (nz + 1)

# Coordinates
X = np.arange(0, lx + 0.1 * dx, dx, dtype='float64')
Y = np.arange(0, ly + 0.1 * dy, dy, dtype='float64')
Z = np.arange(0, lz + 0.1 * dz, dz, dtype='float64')

x = np.zeros((nx + 1, ny + 1, nz + 1))
y = np.zeros((nx + 1, ny + 1, nz + 1))
z = np.zeros((nx + 1, ny + 1, nz + 1))

# We add some random fluctuation to make the grid
# more interesting
for k in range(nz + 1):
    for j in range(ny + 1):
        for i in range(nx + 1):
            x[i, j, k] = X[i] + (0.5 - rnd.random()) * 0.2 * dx
            y[i, j, k] = Y[j] + (0.5 - rnd.random()) * 0.2 * dy
            z[i, j, k] = Z[k] + (0.5 - rnd.random()) * 0.2 * dz

# Variables
pressure = np.random.rand(ncells).reshape((nx, ny, nz))
temp = np.random.rand(npoints).reshape((nx + 1, ny + 1, nz + 1))

gridToVTK("./structured", x, y, z, cellData={
          "pressure": pressure}, pointData={"temp": temp})
Beispiel #37
0
    main.u = myFFT.myifft3D(main.uhat)
    main.v = myFFT.myifft3D(main.vhat)
    main.w = myFFT.myifft3D(main.what)
    if (main.turb_model == 'DNS' or main.turb_model == 'Smagorinsky'):
      np.savez(string2,u=main.u,v=main.v,w=main.w)
    if (main.turb_model == 'FM1'):
      w0_up = myFFT.myifft3D(main.w0_u[:,:,:,0])
      w0_vp = myFFT.myifft3D(main.w0_v[:,:,:,0])
      w0_wp = myFFT.myifft3D(main.w0_w[:,:,:,0])
      np.savez(string2,u=main.u,v=main.v,w=main.w,w0_u=w0_up,w0_v=w0_vp,w0_w=w0_wp)
  
    #main.p = myFFT.myifft3D(main.phat)
    sys.stdout.write("===================================================================================== \n")
    sys.stdout.write('t = '  + str(main.t) + '   Wall time = ' + str(time.time() - t0) + '\n' )
    sys.stdout.write('Div = ' + str( np.linalg.norm(div) )  + '\n')

    sys.stdout.flush()
    
    gridToVTK(string, x,y,z, pointData = {"u" : np.real(main.u.transpose()) , \
      "v" : np.real(main.v.transpose()) , "w" : np.real(main.w.transpose()) } ) #, \
#363       "p" : np.real(pdummy.transpose())} )

  #---------------------------------------------
  # advance by Adams Bashforth/Crank Nicolson
  main.iteration += 1
  advance_AdamsCrank(main,grid,myFFT)
  main.t += main.dt
#========================================================================


Beispiel #38
0
# * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS              *
# * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                    *
# ************************************************************************

# **************************************************************
# * Example of how to use the high level gridToVTK function.   *
# * This example shows how to export a rectilinear grid.       *
# **************************************************************

from evtk.hl import gridToVTK
import numpy as np

# Dimensions
nx, ny, nz = 6, 6, 2
lx, ly, lz = 1.0, 1.0, 1.0
dx, dy, dz = lx / nx, ly / ny, lz / nz

ncells = nx * ny * nz
npoints = (nx + 1) * (ny + 1) * (nz + 1)

# Coordinates
x = np.arange(0, lx + 0.1 * dx, dx, dtype="float64")
y = np.arange(0, ly + 0.1 * dy, dy, dtype="float64")
z = np.arange(0, lz + 0.1 * dz, dz, dtype="float64")

# Variables
pressure = np.random.rand(ncells).reshape((nx, ny, nz))
temp = np.random.rand(npoints).reshape((nx + 1, ny + 1, nz + 1))

gridToVTK("./rectilinear", x, y, z, cellData={"pressure": pressure}, pointData={"temp": temp})
Beispiel #39
0
  data3  = file['/Fields/Bz'][...]
  data4  = file['/Fields/Ex'][...]
  data5  = file['/Fields/Ey'][...]
  data6  = file['/Fields/Ez'][...]
  data7  = file['/Fields/Rho_0'][...]
  data8  = file['/Fields/Rho_1'][...]
  data9  = file['/Fields/Jx_0'][...]
  data10 = file['/Fields/Jy_0'][...]
  data11 = file['/Fields/Jz_0'][...]
  data12 = file['/Fields/Jx_1'][...]
  data13 = file['/Fields/Jy_1'][...]
  data14 = file['/Fields/Jz_1'][...]
  
  # Write the VTK file

  gridToVTK(vtkfilename+"_"+cycle, xc, yc, zc, cellData = {"Bx"    : data1,  \
                                                           "By"    : data2,  \
                                                           "Bz"    : data3,  \
                                                           "Ex"    : data4,  \
                                                           "Ey"    : data5,  \
                                                           "Ez"    : data6,  \
                                                           "Rho_0" : data7,  \
                                                           "Rho_1" : data8,  \
                                                           "Jx_0"  : data9,  \
                                                           "Jy_0"  : data10, \
                                                           "Jz_0"  : data11, \
                                                           "Jx_1"  : data12, \
                                                           "Jy_1"  : data13, \
                                                           "Jz_1"  : data14 })
  
Beispiel #40
0
def write_vtk_2(name,pts,vrbl_r,vrbl_i,eig_num):
	i,j,k = pts
#	names = (name + '_r', name + '_i')
#	vrbl_m = vrbl_r,vrbl_i
	vtk_file_path = gridToVTK( name + "_eigen_%d" % eig_num,i,j,k, pointData = {str(name + '_r'): vrbl_r , str(name + '_i') : vrbl_i})
	return vtk_file_path
x_vals = A**3 / 9
lambdas = A**3 / 9
alphas = A**3 / 9

# Create the meshes that will be used to generate the attributes. The purpose
# of these meshes is to make good use of vectorization.
x_grid = x_vals.reshape(1, 1, len(x_vals))
x_grid = x_grid.repeat(len(lambdas), axis=1)
x_grid = x_grid.repeat(len(alphas), axis=0)
lambda_grid = lambdas.reshape(1, len(lambdas), 1)
lambda_grid = lambda_grid.repeat(len(x_vals), axis=2)
lambda_grid = lambda_grid.repeat(len(alphas), axis=0)
alpha_grid = alphas.reshape(len(alphas), 1, 1)
alpha_grid = alpha_grid.repeat(len(x_vals), axis=2)
alpha_grid = alpha_grid.repeat(len(lambdas), axis=1)

# Create the attribute for G = x^3 + lambda*x + alpha_1*x^2. The alpha_2
# auxiliary parameter will be included using animation in ParaView.
G = x_grid**3 + lambda_grid * x_grid + alpha_grid * x_grid**2

# Create the attribute for G_x = 3*x^2 + lambda + 2*alpha*x
# and use the signum function as a test for stability.
Gx = 3 * x_grid**2 + lambda_grid + 2 * alpha_grid * x_grid
sgn_Gx = np.sign(Gx)

# Use EVTK to create the VTR file.
# The parameters for gridToVtk: (file name, x-coords of mesh, y-coords of mesh,
#                                z-coords of mesh, pointData).
gridToVTK("./pitchforkMesh", alphas, lambdas, x_vals, \
            pointData={"G":G, "stability":sgn_Gx, "G_x":Gx})
Beispiel #42
0
# * Example of how to use the high level gridToVTK function.   *
# * This example shows how to export a rectilinear grid.       *
# **************************************************************

from evtk.hl import gridToVTK
import numpy as np

# Dimensions
nx, ny, nz = 6, 6, 2
lx, ly, lz = 1.0, 1.0, 1.0
dx, dy, dz = lx / nx, ly / ny, lz / nz

ncells = nx * ny * nz
npoints = (nx + 1) * (ny + 1) * (nz + 1)

# Coordinates
x = np.arange(0, lx + 0.1 * dx, dx, dtype='float64')
y = np.arange(0, ly + 0.1 * dy, dy, dtype='float64')
z = np.arange(0, lz + 0.1 * dz, dz, dtype='float64')

# Variables
pressure = np.random.rand(ncells).reshape((nx, ny, nz))
temp = np.random.rand(npoints).reshape((nx + 1, ny + 1, nz + 1))

gridToVTK("./rectilinear",
          x,
          y,
          z,
          cellData={"pressure": pressure},
          pointData={"temp": temp})
Beispiel #43
0
dh_mean = f.root.fris.dh_mean[:]
z = np.arange(0, dh_mean.shape[2], dtype='float64')

f.close()

# Dimensions
'''
nx, ny, nz = 6, 6, 2
lx, ly, lz = 1.0, 1.0, 1.0
dx, dy, dz = lx/nx, ly/ny, lz/nz

ncells = nx * ny * nz
npoints = (nx + 1) * (ny + 1) * (nz + 1)
'''

# Coordinates
'''
x = np.arange(0, lx + 0.1*dx, dx, dtype='float64')
y = np.arange(0, ly + 0.1*dy, dy, dtype='float64')
z = np.arange(0, lz + 0.1*dz, dz, dtype='float64')
'''

# Variables
'''
pressure = np.random.rand(ncells).reshape( (nx, ny, nz))
temp = np.random.rand(npoints).reshape( (nx + 1, ny + 1, nz + 1))
'''

gridToVTK("./rectilinear", x, y, z, cellData = {"dh_mean" : dh_mean}) #, pointData = {"temp" : temp})
#imageToVTK("./image", cellData = {"dh_mean" : zz})#, pointData = {"temp" : z} )
y_slice = 4
z_slice = 6

SIG = np.linspace(sigma0, sigmaN, Nx, dtype='float32')
EPSA = np.linspace(epsilon0, epsilonN, Ny, dtype='float32')
KAPPA = np.linspace(k0, kN, Nz, dtype='float32')

surface = avSlope.reshape((Nx, Ny, Nz))

surfaceFlag = np.require(surface,
                         dtype=np.float32,
                         requirements=['A', 'O', 'W', 'C'])

gridToVTK("./" + file_name,
          SIG,
          EPSA,
          KAPPA,
          pointData={file_name: surfaceFlag})

x_vals = SIG
y_vals = EPSA
z_vals = KAPPA

x_axis = []
y_axis = []
z_axis = []

# for i in range (len(x_vals)):
#     for j in range (len(y_vals)):
#         x_axis=np.append(x_axis,x_vals[i])
#         y_axis=np.append(y_axis,y_vals[j])
Beispiel #45
0
    Nx = len(model.x)
    Ny = len(model.y)
    Nz = len(model.z)

    Xgrid = (np.add.accumulate(np.append([0.], model.x)) +
             model.orig[0]) * scale
    Ygrid = (np.add.accumulate(np.append([0.], model.y)) +
             model.orig[1]) * scale
    Zgrid = (np.add.accumulate(np.append([0.], model.z)) +
             model.orig[2]) * scale

    # in wsinv3Dmodel.py: self.m.shape = (Nz,Ny,Nx)
    gridToVTK(model_file,
              Zgrid,
              Ygrid,
              Xgrid,
              cellData={"resistivity": model.m.copy()})

    # print "# vtk DataFile Version 3.0"
    # print "%s" % model.comment_line
    # print "ASCII"
    # print "DATASET RECTILINEAR_GRID"
    # print "DIMENSIONS %d %d %d" % (Nx,Ny,Nz)
    # print "X_COORDINATES %d float" % Nx
    # print "%s" % print_grid(model.x,model.orig[0])
    # print "Y_COORDINATES %d float" % Ny
    # print "%s" % print_grid(model.y,model.orig[1])
    # print "Z_COORDINATES %d float" % Nz
    # print "%s" % print_grid(model.z,model.orig[2])
    # print "CELL_DATA 1"
Beispiel #46
0
Z = np.arange(0, lz + 0.1*dz, dz, dtype='float64')
'''

x3 = np.zeros((ny, nx, nz))
y3 = np.zeros((ny, nx, nz))
z3 = np.zeros((ny, nx, nz))

'''
# We add some random fluctuation to make the grid
# more interesting
for k in range(nz):
    for j in range(nx):
        for i in range(ny):
            x3[i,j,k], y3[i,j,k] = proj(x[j], y[i])
            #x3[i,j,k] = x[j]
'''

for k in range(16):
    x3[:,:,k] = xx[:]
    y3[:,:,k] = yy[:]
    z3[:,:,k] = k

# Variables
'''
pressure = np.random.rand(ncells).reshape( (nx, ny, nz))
temp = np.random.rand(npoints).reshape( (nx + 1, ny + 1, nz + 1))
'''

print 'x3, y3, z3, dh_mean:', x3.shape, y3.shape, z3.shape, dh_mean.shape
gridToVTK("./structured", x3, y3, z3, cellData = {"dh_mean" : dh_mean}) #, pointData = {"temp" : temp})
Beispiel #47
0
def write_vtk(name,pts,vrbl,t,nx,ny,nz):
	i,j,k = pts
	vrbl = np.array(vrbl)
	vtk_file_path = gridToVTK("./batch/" + name + "_batch_%d" % t, i, j, k, pointData = {str(name) : vrbl})
	return vtk_file_path
Beispiel #48
0
def main():
    """
    Convert ModEM output files (model) into 3D VTK resistivity grid
    
    (distance is given in kilometers)


    Input:
    - ModEM model file 
    - ModEM data file 

    - [optional] VTK resistivity grid file - output file name
    - [optional] VTK station grid file - output file name

    """

    arguments = sys.argv

    if len(arguments) < 2:
        sys.exit('\nERROR - provide at least 1 file name: <model file> [<data>]'\
            ' [out:rho] [out:stations]\n')

    try:
        Mmodel = os.path.abspath(os.path.realpath(arguments[1]))

        try:
            VTKresist = os.path.abspath(os.path.realpath(arguments[3]))
        except:
            VTKresist = os.path.abspath(os.path.realpath('VTKResistivityGrid'))

        try:
            Mdata = os.path.abspath(os.path.realpath(arguments[2]))
        except:
            pass

        try:
            VTKstations = os.path.abspath(os.path.realpath(arguments[4]))
        except:
            VTKstations = os.path.abspath(os.path.realpath('VTKStationGrid'))



    except:
        sys.exit('ERROR - could not find file(s)')


    f = open(Mmodel, 'r')

    # skip first line in file
    f.readline()

    # read X,Y,Z mesh dimensions
    dims = []
    modeldata_firstline = f.readline().split()

    try:
        function =  modeldata_firstline[4].lower()
    except:
        function = None

    for n in range(3):
        dims.append(int(modeldata_firstline[n]))
    size = dims[0]*dims[1]*dims[2]
    print 'Mesh:     ', dims
    print 'Datapoints:     ', size

    # read N,E,D spacing
    #  (depends on line break only after final value)
    spacing = []
    for n in range(3):
        i=0
        while i < dims[n]:
            modeldata_nextlines = f.readline().split()
            for j in modeldata_nextlines:
                spacing.append(float(j)/1000.0)
                i += 1

    # read model values
    #  (depends on line break only after final value)
    mt = np.zeros(size)
    i=0
    while i < size:
        modeldata_morelines = f.readline().split()
        if len(modeldata_morelines) == 0:
            continue
        for j in modeldata_morelines:
            if function is None:
                mt[i] = float(j)
            elif function in ['loge']:
                mt[i] = np.e**(float(j))
            elif function in ['log','log10']:
                mt[i] = 10**(float(j))
            i += 1
    #reading the mesh blocks and calculate coordinates.
    #Coords are taken at the center points of the blocks

    #read the lines following the model:
    appendix = f.readlines()
    
    # the second last non empty line contains a triple that defines the 
    # lower left corner coordinates of the model 
    x0 = None
    for line in appendix[::-1]:
        line = line.strip().split()
        if len(line) != 3:
            continue
        else:
            try:
                x0 = float(line[0])/1000.
                y0 = float(line[1])/1000.
                z0 = float(line[2])/1000.
                break
            except:
                continue
    if x0 is None:
        x0 = 0
        y0 = 0
        z0 = 0 
        print 'Warning - no reference point found - lower left corner of model'\
        ' set to 0,0,0'

    Xspacing = spacing[:dims[0]]

    # calc North coordinates of vtk mesh
    Xdist = 0 # calculate total North distance by summing all blocks
    for i in range(dims[0]):
        Xdist += Xspacing[i]

    X = np.zeros(dims[0])
    #X[0] = -0.5 * Xdist + 0.5*(Xspacing[0])# define zero at the center of the model
    X[0] = 0.5*(Xspacing[0])# define zero at the lower left corner of the model
    for i in range(dims[0]-1):
        local_spacing = 0.5*(Xspacing[i]+Xspacing[i+1])
        X[i+1] = X[i] + local_spacing
    
    #add reference point coordinate
    X += x0

    Yspacing = spacing[dims[0]:dims[0]+dims[1]]
    # calc Yast coordinates of vtk mesh
    Ydist = 0 # calculate total Yast distance by summing all blocks
    for i in range(dims[1]):
        Ydist += Yspacing[i]

    Y = np.zeros(dims[1])
    #Y[0] = -0.5 * Ydist + 0.5*(Yspacing[0])# define zero at the center of the model
    Y[0] = 0.5*(Yspacing[0])# define zero at the lower left corner of the model
    for i in range(dims[1]-1):
        local_spacing = 0.5*(Yspacing[i]+Yspacing[i+1])
        Y[i+1] = Y[i] + local_spacing
    
    #add reference point coordinate
    Y += y0

    Dspacing=spacing[dims[0]+dims[1]:]
    # calc Down coordinates of vtk mesh
    D = np.zeros(dims[2])
    D[0] = 0.5*Dspacing[0]
    for i in range(dims[2]-1):
        local_spacing = 0.5*(Dspacing[i]+Dspacing[i+1])
        D[i+1] = D[i] + local_spacing

    
    #add reference point coordinate
    D+= z0

    # output to vtk format
    # first components read in reverse order!!
    mtNS = np.zeros((dims[0],dims[1],dims[2])) 

    n=0

    #define array for alternative output as csv file, which
    #can be read by paraview directly 
    arr = np.zeros((len(X)*len(Y)*len(D),4))
    
    for idx_D in range(dims[2]):
        for idx_Y in range(dims[1]):
            for idx_X in range(dims[0]):
                #switch North/South by convention
                mtNS[-(idx_X+1),idx_Y,idx_D] = mt[n]
                arr[n,0] = X[idx_X]
                arr[n,1] = Y[idx_Y]
                arr[n,2] = D[idx_D]
                arr[n,3] = mt[n]
                n += 1
    gridToVTK(VTKresist, X, Y, D, pointData = {'resistivity' : mtNS})

    f.close()

    #fn2 = VTKresist+'.csv'
    #F = open(fn2,'w')
    #F.write('X , Y , Down , Rho \n')
    #np.savetxt(F,arr,delimiter=',')
    #F.close()

    #print 'Created Resistivity Array: {0}.csv'.format(VTKresist)
    print 'Created Resistivity VTK File: {0}.vtr'.format(VTKresist)

    try:
        f = open(Mdata, 'r')

        # get stations by parsing all lines that do NOT start with > or #
        rawdata = f.readlines()
        f.close()

        lo_datalines = []
        for l in rawdata:
            if l.strip()[0] not in ['#','>']: 
                lo_datalines.append(l.strip())
    
        lo_coords = []
        for line in lo_datalines:
            line = line.split()
            x = float(line[4])/1000.
            y = float(line[5])/1000.
            z = float(line[6])/1000.
            point = (x,y,z)
            if point not in lo_coords:
                lo_coords.append(point)

        all_coords = np.array(lo_coords)[:]
        print 'Stations:     ', len(all_coords)

        #sorting N->S, W->E
        all_coords = all_coords[np.lexsort((all_coords[:, 1], all_coords[:, 0]))]

        N = np.array(all_coords[:,0])
        E = np.array(all_coords[:,1])
        D = np.array(all_coords[:,2])


        dummy = np.ones(len(all_coords))

        pointsToVTK(VTKstations, N, E, D, data = {"dummyvalue" : dummy})



        print 'Created Station VTK File: {0}.vtu'.format(VTKstations)
    except:
        print 'Could not create Station File '
Beispiel #49
0
#t = 0.2: 0.108
t0 = time.time()
t = 0
et = 20
dt = 1.e-1
Q = zeros((3*N1,3*N2,3*(N3/2+1)),dtype='complex')
Q = U2Q(Q,uhat,vhat,what)
iteration = 0
save_freq = 50
Energy = zeros(1)
Energy[0] = real( mean(0.5*uhat*conj(uhat) + 0.5*vhat*conj(vhat) + 0.5*what*conj(what)) )
EnergyScale = mean( 0.5*(u*u +v*v + w*w) )/Energy[0] 
print(Energy[0])
while t <= et:
  Q = advanceQ_RK4(dt,Q,uhat,vhat,what,grid,myFFT)
  t += dt
  if (iteration%save_freq == 0):
    string = '3DSolution/sol' + str(iteration)
    u = irfftn(uhat)*sqrt(N1*N2*N3)
    v = irfftn(vhat)*sqrt(N1*N2*N3)
    w = irfftn(what)*sqrt(N1*N2*N3)
    gridToVTK(string, grid.x,grid.y,grid.z, pointData = {"u" : real(u.transpose()) , \
      "v" : real(v.transpose()), \
      "w" : real(w.transpose())} ) 
  iteration += 1
  Energy = append(Energy,EnergyScale*mean(0.5*uhat*conj(uhat) + 0.5*vhat*conj(vhat) + 0.5*what*conj(what)))
  print(time.time() - t0,t,Energy[-1])
t1 = time.time()
print('time = ' + str(t1 - t0))
Beispiel #50
0
def main():
    """
    Convert ws3Dinv output files (model and responses) into 3D VTK resistivity grid
    and unstructured VTKGrid containing station locations.

    Input:
    - ws3dInv model name
    - ws3DInv response file name
    - [optional] VTK resistivity grid file - output file name
    - [optional] VTK stations grid file - output file name
    """

    arguments = sys.argv

    if len(arguments) < 3:
        sys.exit(
            'ERROR - provide at least 2 file names: <modeldata file>  <responses file>')

    try:
        WSMTmodel = os.path.abspath(os.path.realpath(arguments[1]))
        WSMTresp = os.path.abspath(os.path.realpath(arguments[2]))

        try:
            VTKresist = os.path.abspath(os.path.realpath(arguments[3]))
        except:
            VTKresist = os.path.abspath(os.path.realpath('VTKResistivityGrid'))

        try:
            VTKstations = os.path.abspath(os.path.realpath(arguments[4]))
        except:
            VTKstations = os.path.abspath(os.path.realpath('VTKStationGrid'))

    except:
        sys.exit('ERROR - could not find file(s)')

    f = open(WSMTmodel, 'r')

    # skip first line in file
    f.readline()

    # read N,E,D mesh dimensions
    dims = []
    modeldata_firstline = f.readline().split()
    for n in range(3):
        dims.append(int(modeldata_firstline[n]))
    size = dims[0] * dims[1] * dims[2]
    print 'Mesh     ', dims
    print 'Data     ', size

    # read N,E,D spacing
    #  (depends on line break only after final value)
    spacing = []
    for n in range(3):
        i = 0
        while i < dims[n]:
            modeldata_nextlines = f.readline().split()
            for j in modeldata_nextlines:
                spacing.append(float(j) / 1000.0)
                i += 1

    # read mt data
    #  (depends on line break only after final value)
    mt = np.zeros(size)
    i = 0
    while i < size:
        modeldata_morelines = f.readline().split()
        for j in modeldata_morelines:
            mt[i] = float(j)
            i += 1

    # calc North coordinates of vtk mesh
    Ndist = 0  # calculate total North distance
    for i in range(dims[0]):
        Ndist += spacing[i]
    N = np.zeros(dims[0] + 1)
    N[0] = -0.5 * Ndist  # zero center of model
    for i in range(dims[0]):
        N[i + 1] = N[i] + spacing[i]

    # calc East coordinates of vtk mesh
    Edist = 0  # calculate total y distance
    for i in range(dims[1]):
        Edist += spacing[dims[0] + i]
    E = np.zeros(dims[1] + 1)
    E[0] = -0.5 * Edist  # zero center of model
    for i in range(dims[1]):
        E[i + 1] = E[i] + spacing[dims[0] + i]

    # calc Down coordinates of vtk mesh
    D = np.zeros(dims[2] + 1)
    D[0] = 0.0
    for i in range(dims[2]):
        D[i + 1] = D[i] + spacing[dims[0] + dims[1] + i]

    # output to vtk format
    # first components read in reverse order!!
    mtNS = np.zeros((dims[0], dims[1], dims[2]))  # North-to-South conversion
    n = 0
    for idx_D in range(dims[2]):
        for idx_E in range(dims[1]):
            for idx_S in range(dims[0]):
                mtNS[(dims[0] - 1) - idx_S, idx_E, idx_D] = mt[n]
                n += 1
    gridToVTK(VTKresist, N, E, D, cellData={'resistivity': mtNS})

    f.close()

    f = open(WSMTresp, 'r')

    # get station count
    respdata_firstline = f.readline().split()
    nstations = int(respdata_firstline[0])
    print 'Stations ', nstations

    # read North locations
    f.readline()  # skip line
    N = np.zeros(nstations)
    i = 0
    while i < nstations:
        respdata_nextlines = f.readline().split()
        for j in respdata_nextlines:
            N[i] = float(j) / 1000.0
            i += 1

    # read East locations
    f.readline()  # skip line
    E = np.zeros(nstations)
    i = 0
    while i < nstations:
        respdata_morelines = f.readline().split()
        for j in respdata_morelines:
            E[i] = float(j) / 1000.0
            i += 1
    f.close()

    # set Depths -- all stations at the surface!!
    D = np.zeros(nstations)

    # output to vtk format - dummy value for scalar field needed
    dummy = np.ones(nstations)
    # for j in range(nstations):
    #    dummy[j] = 1.0

    print np.shape(dummy), np.shape(N), np.shape(E), np.shape(D)

    pointsToVTK(VTKstations, N, E, D, data={"dummyvalue": dummy})

    print 'Created Resistivity File: {0}.vtr '.format(VTKresist)
    print 'Created Station File: {0}.vtu '.format(VTKstations)
Beispiel #51
0
Z = np.arange(0, lz + 0.1*dz, dz, dtype='float64')
'''

x3 = np.zeros((ny, nx, nz))
y3 = np.zeros((ny, nx, nz))
z3 = np.zeros((ny, nx, nz))
'''
# We add some random fluctuation to make the grid
# more interesting
for k in range(nz):
    for j in range(nx):
        for i in range(ny):
            x3[i,j,k], y3[i,j,k] = proj(x[j], y[i])
            #x3[i,j,k] = x[j]
'''

for k in range(16):
    x3[:, :, k] = xx[:]
    y3[:, :, k] = yy[:]
    z3[:, :, k] = k

# Variables
'''
pressure = np.random.rand(ncells).reshape( (nx, ny, nz))
temp = np.random.rand(npoints).reshape( (nx + 1, ny + 1, nz + 1))
'''

print 'x3, y3, z3, dh_mean:', x3.shape, y3.shape, z3.shape, dh_mean.shape
gridToVTK("./structured", x3, y3, z3,
          cellData={"dh_mean": dh_mean})  #, pointData = {"temp" : temp})
Beispiel #52
0
def main():
    """
    Convert ws3Dinv output files (model and responses) into 3D VTK resistivity grid
    and unstructured VTKGrid containing station locations.

    Input:
    - ws3dInv model name
    - ws3DInv response file name
    - [optional] VTK resistivity grid file - output file name
    - [optional] VTK stations grid file - output file name
    """

    arguments = sys.argv

    if len(arguments) < 3:
        sys.exit('ERROR - provide at least 2 file names: <modeldata file>  <responses file>')

    try:
        WSMTmodel = os.path.abspath(os.path.realpath(arguments[1]))
        WSMTresp  = os.path.abspath(os.path.realpath(arguments[2]))

        try:
            VTKresist = os.path.abspath(os.path.realpath(arguments[3]))
        except:
            VTKresist = os.path.abspath(os.path.realpath('VTKResistivityGrid'))

        try:
            VTKstations = os.path.abspath(os.path.realpath(arguments[4]))
        except:
            VTKstations = os.path.abspath(os.path.realpath('VTKStationGrid'))


    except:
        sys.exit('ERROR - could not find file(s)')


    f = open(WSMTmodel, 'r')

    # skip first line in file
    f.readline()

    # read N,E,D mesh dimensions
    dims = []
    modeldata_firstline = f.readline().split()
    for n in range(3):
        dims.append(int(modeldata_firstline[n]))
    size = dims[0]*dims[1]*dims[2]
    print 'Mesh     ', dims
    print 'Data     ', size

    # read N,E,D spacing
    #  (depends on line break only after final value)
    spacing = []
    for n in range(3):
        i=0
        while i < dims[n]:
            modeldata_nextlines = f.readline().split()
            for j in modeldata_nextlines:
                spacing.append(float(j)/1000.0)
                i += 1

    # read mt data
    #  (depends on line break only after final value)
    mt = np.zeros(size)
    i=0
    while i < size:
        modeldata_morelines = f.readline().split()
        for j in modeldata_morelines:
            mt[i] = float(j)
            i += 1

    # calc North coordinates of vtk mesh
    Ndist = 0 # calculate total North distance
    for i in range(dims[0]):
        Ndist += spacing[i]
    N = np.zeros(dims[0]+1)
    N[0] = -0.5 * Ndist # zero center of model
    for i in range(dims[0]):
        N[i+1] = N[i] + spacing[i]

    # calc East coordinates of vtk mesh
    Edist = 0 # calculate total y distance
    for i in range(dims[1]):
        Edist += spacing[dims[0] + i]
    E = np.zeros(dims[1]+1)
    E[0] = -0.5 * Edist # zero center of model
    for i in range(dims[1]):
        E[i+1] = E[i] + spacing[dims[0] + i]

    # calc Down coordinates of vtk mesh
    D = np.zeros(dims[2]+1)
    D[0] = 0.0
    for i in range(dims[2]):
        D[i+1] = D[i] + spacing[dims[0] + dims[1] + i]

    # output to vtk format
    # first components read in reverse order!!
    mtNS = np.zeros((dims[0],dims[1],dims[2])) # North-to-South conversion
    n=0
    for idx_D in range(dims[2]):
        for idx_E in range(dims[1]):
            for idx_S in range(dims[0]):
                mtNS[(dims[0]-1)-idx_S,idx_E,idx_D] = mt[n]
                n += 1
    gridToVTK(VTKresist, N, E, D, cellData = {'resistivity' : mtNS})

    f.close()

    f = open(WSMTresp, 'r')

    # get station count
    respdata_firstline = f.readline().split()
    nstations = int(respdata_firstline[0])
    print 'Stations ', nstations

    # read North locations
    f.readline() #skip line
    N = np.zeros(nstations)
    i=0
    while i < nstations:
        respdata_nextlines = f.readline().split()
        for j in respdata_nextlines:
            N[i] = float(j)/1000.0
            i += 1

    # read East locations
    f.readline() #skip line
    E = np.zeros(nstations)
    i=0
    while i < nstations:
        respdata_morelines = f.readline().split()
        for j in respdata_morelines:
            E[i] = float(j)/1000.0
            i += 1
    f.close()


    # set Depths -- all stations at the surface!!
    D = np.zeros(nstations)

    # output to vtk format - dummy value for scalar field needed
    dummy = np.ones(nstations)
    #for j in range(nstations):
    #    dummy[j] = 1.0

    print np.shape(dummy),np.shape(N),np.shape(E),np.shape(D)

    pointsToVTK(VTKstations, N, E, D, data = {"dummyvalue" : dummy})



    print 'Created Resistivity File: {0}.vtr '.format(VTKresist)
    print 'Created Station File: {0}.vtu '.format(VTKstations)
Beispiel #53
0
def initial_setup(nu, nv, nw):
    #--------------------------------------------------------------
    #
    # Read in the boundary conditions file and save variables
    #
    #--------------------------------------------------------------

    # Read in boundary condition file!
    bcfile = open('boundary_conditions.txt', 'r')
    input_data = bcfile.readlines()
    bcfile.close()

    # Skip the header and proceed with the initialization!
    line_2 = input_data[1].split()
    rgas = np.float(line_2[2])

    line_3 = input_data[2].split()
    gamma = np.float(line_3[2])

    line_4 = input_data[3].split()
    pressure_stag_inlet = np.float(line_4[2])

    line_5 = input_data[4].split()
    temp_stag_inlet = np.float(line_5[2])

    line_6 = input_data[5].split()
    alpha_1 = np.float(line_6[2])

    line_7 = input_data[6].split()
    pressure_static_exit = np.float(line_7[2])

    line_8 = input_data[7].split()
    cfl = np.float(line_8[2])

    line_9 = input_data[8].split()
    smooth_fac_input = np.float(line_9[2])

    line_10 = input_data[9].split()
    nsteps = np.float(line_10[2])

    line_11 = input_data[10].split()
    conlim_in = np.float(line_11[2])

    boundary_conditions = [rgas, gamma, pressure_stag_inlet, temp_stag_inlet, alpha_1, pressure_static_exit, cfl ,  smooth_fac_input, nsteps, conlim_in ]

    #----------------------------------------------
    #
    # Setup other variables!
    #
    #----------------------------------------------
    cp = rgas * gamma / (gamma - 1.0)
    cv = cp / (gamma * 1.0)
    gamma_factor = (gamma - 1.0) / (gamma * 1.0)

    #----------------------------------------------
    #
    # Here we initialize the flow variables!
    #
    #-----------------------------------------------
    ro = np.zeros((nv, nu, nw)) # Density
    ro_vel_x = np.zeros((nv, nu, nw)) # Density * Velocity in "x" direction
    ro_vel_y = np.zeros((nv, nu, nw)) # Density * Velocity in "y" direction
    pressure = np.zeros((nv, nu, nw)) # static pressure
    ro_energy = np.zeros((nv, nu, nw)) # Density * energy
    vel_x = np.zeros((nv, nu, nw)) # velocity-x
    vel_y = np.zeros((nv, nu, nw)) # velocity-y
    enthalpy_stag = np.zeros((nv, nu, nw)) # Stagnation enthalpy

    #----------------------------------------------
    #
    # Here we initialize the fluxes!
    #
    #-----------------------------------------------
    flux_i_mass = np.zeros((nv, nu)) # Mass
    flux_j_mass = np.zeros((nv, nu))

    flux_i_xmom = np.zeros((nv, nu)) # X-MOMENTUM
    flux_j_xmom = np.zeros((nv, nu))

    flux_i_ymom = np.zeros((nv, nu)) # Y-MOMENTUM
    flux_j_ymom = np.zeros((nv, nu))

    flux_i_enthalpy = np.zeros((nv, nu)) # Enthalpy
    flux_j_enthalpy = np.zeros((nv, nu))

    flow = np.zeros((nu, 1)) # total mass flow rate across each "i"

    #----------------------------------------------
    #
    # new guess subroutine
    #
    #-----------------------------------------------
    jmid = nv / 2.0
    temp_static_exit = temp_stag_inlet * (pressure_static_exit/pressure_stag_inlet)**gamma_factor
    vel_exit = np.sqrt(2 * cp * (temp_stag_inlet - temp_static_exit))
    ro_exit = pressure_static_exit / rgas / temp_static_exit
    pressure_static_inlet = 55000
    temp_static_inlet = temp_stag_inlet * (pressure_static_inlet / pressure_stag_inlet)**gamma_factor
    vel_inlet = np.sqrt(2 * cp * (temp_stag_inlet - temp_static_inlet))
    ro_inlet = pressure_static_inlet / rgas / temp_static_inlet

    # Get the grid!
    grid_parameters = create_grid(nu, nv, nw)
    point_x = grid_parameters[0]
    point_y = grid_parameters[1]
    point_z = grid_parameters[2]

    # Initial guess!
    for j in range(0, nv):
        for i in range(0, nu):
            ro[j,i,0] = 1.2
            ro_vel_x[j,i,0] = 100 * (i * 1.0)/(nu * 1.0)
            ro_vel_y[j,i,0] = 0.0
            pressure[j,i,0] = 100000 * (0.9 + 0.1 * (i * 1.0)/(nu * 1.0))
            enthalpy_stag[j,i,0] = 300000
            ro_energy[j,i,0] = pressure[j,i,0] / (gamma - 1.0)


    for j in range(0, nv):
        for i in range(0, nu-1):
            dx = point_x[jmid, i+1, 0] - point_x[jmid, i, 0]
            dy = point_y[jmid, i+1, 0] - point_y[jmid, i, 0]
            ds = np.sqrt(dx*dx + dy*dy)

            vel_local = vel_inlet + (vel_exit - vel_inlet)* (1.0 * (i-1.0)/(nu - 1.0) )
            ro_local = ro_inlet + (ro_exit - ro_inlet)* (1.0 * (i-1.0)/(nu - 1.0) )
            temp_local = temp_static_inlet + (temp_static_exit - temp_static_inlet)* (1.0 * (i-1.0)/(nu - 1.0) )


            velx = vel_local * dx / ds
            vely = vel_local * dy / ds

            ro_vel_x[j,i,0] = ro_local * velx
            ro_vel_y[j,i,0] = ro_local * vely
            ro[j,i,0] = ro_local
            ro_energy[j,i,0] = ro_local * (cv * temp_local + 0.5 * vel_local * vel_local)

        ro_vel_x[j,nu-1,0] = ro_vel_x[j,nu-2,0]
        ro_vel_y[j,nu-1,0] = ro_vel_y[j,nu-2,0]
        ro[j,nu-1,0] = ro[j,nu-2,0]
        ro_energy[j,nu-1,0] = ro_energy[j,nu-2,0]


    #-------------------------------------------------------------------------
    #
    # Output initial flow solution with grid
    #
    #-------------------------------------------------------------------------
    gridToVTK("./initial_flow", point_x, point_y, point_z, pointData={"pressure": pressure, "density": ro, "density-velx": ro_vel_x })

    #-------------------------------------------------------------------------
    #
    # Setting primary & secondary flow variables
    #
    #-------------------------------------------------------------------------
    primary_variables = {}
    secondary_variables = {}
    primary_variables[0] = ro
    primary_variables[1] = ro_vel_x
    primary_variables[2] = ro_vel_y
    primary_variables[3] = ro_energy
    secondary_variables[0] = vel_x
    secondary_variables[1] = vel_y
    secondary_variables[2] = pressure
    secondary_variables[3] = enthalpy_stag

    #-------------------------------------------------------------------------
    #
    # Setting the fluxes
    #
    #-------------------------------------------------------------------------
    fluxes = {}
    fluxes[0] = flux_i_mass
    fluxes[1] = flux_j_mass
    fluxes[2] = flux_i_xmom
    fluxes[3] = flux_j_xmom
    fluxes[4] = flux_i_ymom
    fluxes[5] = flux_j_ymom
    fluxes[6] = flux_i_enthalpy
    fluxes[7] = flux_j_enthalpy
    fluxes[8] = flow

    secondary_variables = set_other_variables(primary_variables, secondary_variables, boundary_conditions, grid_parameters)

    return primary_variables, secondary_variables, fluxes, boundary_conditions, grid_parameters