def tracers_to_vtu(model,dest, overwrite=False): from field import TRACERS # Calculate the number of timesteps LOG.debug('The model run completed %d timesteps',model.total_timesteps) LOG.debug('There should be %d frames available',model.frames) frames=model.frames #result=[] field=TRACERS LOG.debug('Processing field %s',field.name) for frame in range(frames): tracer_filename=os.path.join(model.dir,model.output_file_stem)+'_'+field.prefix+'%05d'%frame vtu_fileout=os.path.join(dest,field.prefix+'%05d'%frame) vtu_filename=vtu_fileout+'.vtu' if os.path.exists(vtu_filename): if overwrite: LOG.debug('Overwriting %s',vtu_filename) else: LOG.debug('Skipping existing file %s',vtu_filename) continue LOG.debug('Processing %s',vtu_filename) tra=read_tracers(tracer_filename) tracers=tra['tracers'] data={tra['varnames'][n]:tracers[:,n] for n in range(3,tra['vars'])} LOG.debug("data: %s",data) pointsToVTK(vtu_fileout,tracers[:,0],tracers[:,1],tracers[:,2],data=data)
def save( self, matlist, idx, dw ): fName = self.fname + str(idx).zfill(self.nzeros) x = []; y = []; v = []; ms = []; matid = [] for mat in matlist: dwi = mat.dwi px,pv,pVS,pVol = dw.getMult( ['px','pxI','pVS','pVol'], dwi ) nn = len(pVol) matid += [dwi]*nn x += list(px[:,0]) y += list(px[:,1]) vx = pv[:,0] vy = pv[:,1] v += list( np.sqrt( vx*vx + vy*vy ) * np.sign(vx) ) pS = [pVS[ii]/pVol[ii] for ii in range(nn)] ms += [vonMises(pp) for pp in pS] x = np.array(x) y = np.array(y) z = np.zeros(x.shape) v = np.array(v) ms = np.array(ms) matid = np.array(matid) vsdat = {"vonMises":ms, "v":v, "mat":matid} pointsToVTK(fName, x, y, z, data = vsdat)
def save(self, matlist, idx, dw): fName = self.fname + str(idx).zfill(self.nzeros) x = [] y = [] v = [] ms = [] matid = [] for mat in matlist: dwi = mat.dwi px, pv, pVS, pVol = dw.getMult(['px', 'pxI', 'pVS', 'pVol'], dwi) nn = len(pVol) matid += [dwi] * nn x += list(px[:, 0]) y += list(px[:, 1]) vx = pv[:, 0] vy = pv[:, 1] v += list(np.sqrt(vx * vx + vy * vy) * np.sign(vx)) pS = [pVS[ii] / pVol[ii] for ii in range(nn)] ms += [vonMises(pp) for pp in pS] x = np.array(x) y = np.array(y) z = np.zeros(x.shape) v = np.array(v) ms = np.array(ms) matid = np.array(matid) vsdat = {"vonMises": ms, "v": v, "mat": matid} pointsToVTK(fName, x, y, z, data=vsdat)
def to_vtk(self, filename): """ Writes the simulation domain to a VTK file. Note that evtk is required! """ from evtk.hl import pointsToVTK # x = np.ascontiguousarray(self.pos[:,0]) # y = np.ascontiguousarray(self.pos[:,1]) # z = np.ascontiguousarray(self.pos[:,2]) x = np.asfortranarray(self.pos[:, 0]) y = np.asfortranarray(self.pos[:, 1]) z = np.asfortranarray(self.pos[:, 2]) radius = np.asfortranarray(self.radius) mass = np.asfortranarray(self.mass) id = np.asfortranarray(self.id) pointsToVTK(filename, x, y, z, data={ "id": id, "radius": radius, "mass": mass }) return
def write_to_vtk2D(cents, displacement, file_name): """ writes 2D data to VTK """ x, y = cents.T x = np.copy(x, order='c') y = np.copy(y, order='c') z = np.zeros(len(x), order='c') if displacement is None: pointsToVTK(file_name, x, y, z, data={"x": x, "y": y}) else: dispX, dispY = displacement.T dispX = np.array(dispX, order='c') dispY = np.array(dispY, order='c') pointsToVTK(file_name, x, y, z, data={ "x": x, "y": y, "dispX": dispX, "dispY": dispY }) pass
def write_to_vtk3D(cents, displacement, file_name): """ writes 3D data to vtk file """ x, y, z = cents.T x = np.array(x, order='c') y = np.array(y, order='c') z = np.array(z, order='c') if displacement is None: pointsToVTK(file_name, x, y, z, data={"x": x, "y": y, "z": z}) else: dispX, dispY, dispZ = displacement.T dispX = np.array(dispX, order='c') dispY = np.array(dispY, order='c') dispZ = np.array(dispZ, order='c') pointsToVTK(file_name, x, y, z, data={ "x": x, "y": y, "z": z, "dispX": dispX, "dispY": dispY, "dispZ": dispZ }) pass
def convert_mesh(fname): f1 = open(fname + '.msh', 'r') # open the mesh file # get the mesh coordinates for line in f1: if line.startswith("$Nodes"): break pcount = int(f1.next()) xyz = np.empty([3, pcount]) for t in range(pcount): v = f1.next().split() xyz[0,t] = float(v[1]) xyz[1,t] = float(v[2]) xyz[2,t] = float(v[3]) # get "distance to nearest lumen" data for line in f1: if line.startswith('"distance to nearest lumen"'): break for t in range(6): # skip 6 lines f1.next() dnl = np.empty(pcount) for t in range(pcount): v = f1.next().split() dnl[t] = float(v[1]) f1.close # close the mesh file # write out to vtk file d = {} d["dnl"] = dnl pointsToVTK(fname, xyz[0,:], xyz[1,:], xyz[2,:], data = d) # write out vtk file
def convert_mesh(fname): f1 = open(fname + '.msh', 'r') # open the mesh file # get the mesh coordinates for line in f1: if line.startswith("$Nodes"): break pcount = int(f1.next()) xyz = np.empty([3, pcount]) for t in range(pcount): v = f1.next().split() xyz[0, t] = float(v[1]) xyz[1, t] = float(v[2]) xyz[2, t] = float(v[3]) # get "distance to nearest lumen" data for line in f1: #if line.startswith('"distance to nearest lumen"'): break if line.startswith('"nearest cell number"'): break for t in range(6): # skip 6 lines f1.next() dnl = np.empty(pcount) for t in range(pcount): v = f1.next().split() dnl[t] = float(v[1]) f1.close # close the mesh file # write out to vtk file d = {} #d["ncn"] = dnl print xyz[0, :].shape print dnl.shape pointsToVTK(fname, xyz[0, :], xyz[1, :], xyz[2, :], data=d) # write out vtk file
def save_structured_vtu(self, filename, struc_grid): from evtk.hl import pointsToVTK filename = filename.replace(".vtu", "") xs, ys, zs = self.__get_grid_locations(struc_grid) data = self.__get_grid_data(struc_grid) pointsToVTK(filename, xs, ys, zs, data)
def saveNodeData( self, fName ): gx = copy(self.gx[:][:,0]) gy = copy(self.gx[:][:,1]) gz = np.zeros(gx.shape) ax = copy(self.ga[:][:,0]) ay = copy(self.ga[:][:,1]) aa = np.sqrt( ax*ax + ay*ay ) vsdat = {"ax":ax, "ay":ay, "aa":aa} pointsToVTK(fName, gx, gy, gz, data = vsdat)
def saveNodeData(self, fName): gx = copy(self.gx[:][:, 0]) gy = copy(self.gx[:][:, 1]) gz = np.zeros(gx.shape) ax = copy(self.ga[:][:, 0]) ay = copy(self.ga[:][:, 1]) aa = np.sqrt(ax * ax + ay * ay) vsdat = {"ax": ax, "ay": ay, "aa": aa} pointsToVTK(fName, gx, gy, gz, data=vsdat)
def generate_points(data, filename): #TODO: Still cannot visualize points well from evtk.hl import pointsToVTK x, y, z = data.T # Sometimes np.arrays could have manipulated to no longer # be c-continuous os we have to impose it x = np.ascontiguousarray(x) y = np.ascontiguousarray(y) z = np.ascontiguousarray(z) pointsToVTK(filename, x, y, z)
def write_points(fname, verts, pdata=None): nverts = verts.shape[0] xyz = np.empty([3, nverts]) # needs re-ordering for i in range(nverts): for j in range(3): xyz[j, i] = verts[i, j] pointsToVTK(fname, \ xyz[0,:], xyz[1,:], xyz[2,:], \ data=pdata) # write out vtu file return
def saveVtk(v, nln): v = np.transpose(v) x = np.array(v[0,:]) # deep copy required y = np.array(v[1,:]) z = np.array(v[2,:]) ncn = np.array(v[3,:]) d = {} d["ncn"] = ncn # nearest cell number d["nln"] = nln # nearest line number pointsToVTK("./tree", x, y, z, data = d) # write out vtk file return
def saveVtk(v, nln): v = np.transpose(v) x = np.array(v[0, :]) # deep copy required y = np.array(v[1, :]) z = np.array(v[2, :]) ncn = np.array(v[3, :]) d = {} d["ncn"] = ncn # nearest cell number d["nln"] = nln # nearest line number pointsToVTK("./tree", x, y, z, data=d) # write out vtk file return
def savePointData( self, fName ): px = copy(self.px[:,0]) py = copy(self.px[:,1]) pz = np.zeros(px.shape) vx = self.pxI[:][:,0] vy = self.pxI[:][:,1] vv = np.sqrt( vx*vx + vy*vy ) * np.sign(vx) pS = [self.pVS[ii]/self.pVol[ii] for ii in range(len(self.pVol))] mises = np.array([vonMises(ii) for ii in pS]) vsdat = {"vonMises":mises, "v":vv, "mat":self.pMat} pointsToVTK(fName, px, py, pz, data = vsdat)
def savePointData(self, fName): px = copy(self.px[:, 0]) py = copy(self.px[:, 1]) pz = np.zeros(px.shape) vx = self.pxI[:][:, 0] vy = self.pxI[:][:, 1] vv = np.sqrt(vx * vx + vy * vy) * np.sign(vx) pS = [self.pVS[ii] / self.pVol[ii] for ii in range(len(self.pVol))] mises = np.array([vonMises(ii) for ii in pS]) vsdat = {"vonMises": mises, "v": vv, "mat": self.pMat} pointsToVTK(fName, px, py, pz, data=vsdat)
def data2vtkstationsgrid(ModEMdatafn, VTKfn='VTKstations'): """ Convert ModEM data file into 2D VTK station set (unstructured grid) Input: - ModEM data file name - [optional] VTK station grid file - output file name """ if not os.path.isfile(os.path.abspath(os.path.realpath(ModEMdatafn))): sys.exit('ERROR - could not find file:\n%s'%(os.path.abspath(os.path.realpath(ModEMdatafn)))) if not os.path.isfile(os.path.abspath(os.path.realpath(VTKfn))): VTKfn = os.path.abspath(os.path.realpath('VTKstations')) F = open(ModEMdatafn, 'r') raw_data = F.readlines() F.close() lo_stations = [] stations_dict = {} lo_norths= [] lo_easts = [] for tmp_line in raw_data: linelist = tmp_line.strip().split() if len(linelist) == 11: tmp_station = linelist[1] tmp_north = float(linelist[4]) tmp_east = float(linelist[5]) if not tmp_station in lo_stations: lo_stations.append(tmp_station) stations_dict[tmp_station] = [tmp_north,tmp_east] lo_norths.append(tmp_north) lo_easts.append(tmp_east) #convert m to km N = np.array(lo_norths)/1000. E = np.array(lo_easts)/1000. D = np.zeros((len(lo_norths))) #dummy scalar values dummy = np.ones((len(lo_norths))) pointsToVTK(VTKfn, N, E, D, data = {"value" : dummy}) print('Created Station File: ',VTKfn)
def data2vtkstationsgrid(ModEMdatafn, VTKfn='VTKstations'): """ Convert ModEM data file into 2D VTK station set (unstructured grid) Input: - ModEM data file name - [optional] VTK station grid file - output file name """ if not os.path.isfile(os.path.abspath(os.path.realpath(ModEMdatafn))): sys.exit('ERROR - could not find file:\n%s' % (os.path.abspath(os.path.realpath(ModEMdatafn)))) if not os.path.isfile(os.path.abspath(os.path.realpath(VTKfn))): VTKfn = os.path.abspath(os.path.realpath('VTKstations')) F = open(ModEMdatafn, 'r') raw_data = F.readlines() F.close() lo_stations = [] stations_dict = {} lo_norths = [] lo_easts = [] for tmp_line in raw_data: linelist = tmp_line.strip().split() if len(linelist) == 11: tmp_station = linelist[1] tmp_north = float(linelist[4]) tmp_east = float(linelist[5]) if not tmp_station in lo_stations: lo_stations.append(tmp_station) stations_dict[tmp_station] = [tmp_north, tmp_east] lo_norths.append(tmp_north) lo_easts.append(tmp_east) # convert m to km N = np.array(lo_norths) / 1000. E = np.array(lo_easts) / 1000. D = np.zeros((len(lo_norths))) # dummy scalar values dummy = np.ones((len(lo_norths))) pointsToVTK(VTKfn, N, E, D, data={"value": dummy}) print 'Created Station File: ', VTKfn
def save_structured_vtu(self, filename, struc_grid, data=None, field="Pressure"): """Function to save structured vtu grid Arguments: filename (str/fp) - location to save vtu file struct_grid (sg) - sg to give locations and (optionally) the data too data_grid (sg) Optional - sg providing the data """ from evtk.hl import pointsToVTK filename = filename.replace(".vtu", "") xs, ys, zs = self.__get_grid_locations(struc_grid) if data is None: data = self.__get_grid_data(struc_grid) #assert isinstance(data, type(np.array)) data = {field: data} pointsToVTK(filename, xs, ys, zs, data)
def to_vtk(self, filename): """ Writes the simulation domain to a VTK file. Note that evtk is required! """ from evtk.hl import pointsToVTK # x = np.ascontiguousarray(self.pos[:,0]) # y = np.ascontiguousarray(self.pos[:,1]) # z = np.ascontiguousarray(self.pos[:,2]) x = np.asfortranarray(self.pos[:,0]) y = np.asfortranarray(self.pos[:,1]) z = np.asfortranarray(self.pos[:,2]) radius = np.asfortranarray(self.radius) mass = np.asfortranarray(self.mass) id = np.asfortranarray(self.id) pointsToVTK(filename, x, y, z, data = {"id" : id, "radius" : radius, "mass": mass}) return
def Points1d(x, y, z, data, OutFileName): # make general *args, kwargs type #points = np.array([x,y,z]).T #data = np.array(data) # #mesh = tvtk.PolyData(points=points) #mesh.point_data.scalars = data #mesh.point_data.scalars.name = 'Data' # # #fileOut = OutFileName+'.vtp' #print fileOut #w = tvtk.XMLPolyDataWriter(input=mesh, file_name=fileOut) #w.write() # #pressure = np.random.rand(npoints) #temp = np.random.rand(npoints) fileOut = OutFileName print OutFileName + '.vtu' #pointsToVTK(fileOut, x, y, z, data = {"r" : data, "pressure" : pressure}) pointsToVTK(fileOut, x, y, z, data={"data": data})
# * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * # * BUT NOT LIMITED TO, PROCUREMEN OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * # * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * # * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * # * 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 pointsToVTK function. * # ************************************************************** from evtk.hl import pointsToVTK import numpy as np # Example 1 npoints = 100 x = np.random.rand(npoints) y = np.random.rand(npoints) z = np.random.rand(npoints) pressure = np.random.rand(npoints) temp = np.random.rand(npoints) pointsToVTK("./rnd_points", x, y, z, data = {"temp" : temp, "pressure" : pressure}) # Example 2 x = np.arange(1.0,10.0,0.1) y = np.arange(1.0,10.0,0.1) z = np.arange(1.0,10.0,0.1) pointsToVTK("./line_points", x, y, z, data = {"elev" : z})
) station_loc = np.loadtxt( sfn, skiprows=6, dtype=[ ("lat", np.float), ("lon", np.float), ("north", np.float), ("east", np.float), ("rel_north", np.float), ("rel_east", np.float), ("elev", np.float), ], ) pointsToVTK( os.path.join(r"c:\Users\jpeacock\Documents\LV\lv_3d_models", "dawson_teleseismic_loc_lvc16"), station_loc["rel_east"].copy() - grid_shift[0], station_loc["rel_north"].copy() - grid_shift[1], station_loc["elev"].copy() / 1000, data={"elev": station_loc["elev"].copy() / 1000}, ) # kml_obj = skml.Kml() # for s_arr in station_loc: # kml_obj.newpoint(coords=[(-s_arr['lon'], s_arr['lat'], s_arr['elev'])]) # # kml_obj.save(os.path.join(os.path.dirname(vfn), 'dawson_teleseismic_stations.kml'))
], ) # compute easting and northing for ii in range(df.shape[0]): e, n, z = gis_tools.project_point_ll2utm(df.lat[ii], df.lon[ii]) vtk_arr[ii]["east"] = (e - model_center[0]) / 1000.0 vtk_arr[ii]["north"] = (n - model_center[1]) / 1000.0 vtk_arr[ii]["depth"] = df.depth[ii] vtk_arr[ii]["mag"] = df.mag[ii] pointsToVTK( r"c:\Users\jpeacock\Documents\ClearLake\EQ_DD_locations", vtk_arr["north"], vtk_arr["east"], vtk_arr["depth"], data={ "mag": vtk_arr["mag"], "depth": vtk_arr["depth"] }, ) # write kml file to check the accuracy kml = skml.Kml() for ss in np.arange(0, df.shape[0], 5): pnt = kml.newpoint(coords=[(df.lon[ss], df.lat[ss])]) kml.save(r"c:\Users\jpeacock\Documents\ClearLake\EQ_DD_locations_2018.kml") # write text file df.to_csv( r"c:\Users\jpeacock\Documents\ClearLake\EQ_DD_locations_2018.csv",
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 '
s_array = s_array[np.where((s_array['lat'] <= 38.4) & (s_array['lat'] >= 37.50))] s_array = s_array[np.where((s_array['lon'] >= -119.25) & (s_array['lon'] <= -118.7))] #print east_0, north_0 east = np.zeros(s_array.shape[0]) north = np.zeros(s_array.shape[0]) depth = [] mag = [] for ii, ss in enumerate(s_array): ee, nn, zz = gis_tools.project_point_ll2utm(ss['lat'], ss['lon']) east[ii] = (ee - east_0) / 1000. north[ii] = (nn - north_0) / 1000. x = north.copy() y = east.copy() z = s_array['depth'].copy() mag = s_array['mag'].copy() pointsToVTK(r"c:\Users\jpeacock\Documents\MonoBasin\EQ_DD_locations_mlc", x, y, z, data={ 'mag': mag, 'depth': z })
# make a new array with easting and northing vtk_arr = np.zeros_like(s_array, dtype=[('east', np.float), ('north', np.float), ('depth', np.float), ('mag', np.float)]) for ii, ss in enumerate(s_array): e, n, z = gis_tools.project_point_ll2utm(ss['lat'], ss['lon']) vtk_arr[ii]['east'] = (e-model_center[0])/1000. vtk_arr[ii]['north'] = (n-model_center[1])/1000. vtk_arr[ii]['depth'] = ss['depth'] vtk_arr[ii]['mag'] = ss['mag'] pointsToVTK(r"c:\Users\jpeacock\Documents\ClearLake\egs_eq_locations", vtk_arr['north'], vtk_arr['east'], vtk_arr['depth'], data={'mag':vtk_arr['mag'], 'depth':vtk_arr['depth']}) # write text file txt_lines = ['ID,lat,lon,depth,mag'] for ii, s_arr in enumerate(s_array): txt_lines.append('{0},{1:.6f},{2:.6f},{3:.2f},{4:.2f}'.format(ii, s_arr['lat'], s_arr['lon'], s_arr['depth'], s_arr['mag'])) with open(r"c:\Users\jpeacock\Documents\ClearLake\egs_eq_locations.csv", 'w') as fid: fid.write('\n'.join(txt_lines))
# --------------------------------------------------- # eq_fn = r"/mnt/hgfs/jpeacock/Documents/Geothermal/Washington/MSH/mshn_earthquake_locations_ll.csv" eq_fn = r"c:\Users\jpeacock\Documents\Geothermal\Washington\eq_psns_all_msh.csv" sv_path = os.path.dirname(eq_fn) # -------------------------------------- eq_df = pd.read_csv(eq_fn) # model center # east_0 = 555703.-253 # north_0 = 5132626.0+26 east_0 = 562012.0 north_0 = 5128858.0 x = np.zeros_like(eq_df.Lat) y = np.zeros_like(eq_df.Lon) for lat, lon, index in zip(eq_df.Lat, eq_df.Lon, range(x.size)): east, north, zone = gis_tools.project_point_ll2utm(lat, lon) x[index] = (east - east_0) / 1000.0 y[index] = (north - north_0) / 1000.0 pointsToVTK( eq_fn[:-4] + "shz", y, x, np.array(eq_df.Depth), data={"depth": np.array(eq_df.Depth), "magnitude": np.array(eq_df.Magnitude)}, )
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 '
x = np.zeros(line_arr.shape[0]) y = np.zeros(line_arr.shape[0]) z = np.zeros(line_arr.shape[0]) mag = np.zeros(line_arr.shape[0]) #east_0 = 334460.0 #north_0 = 4173370.0 east_0 = 336800.0 north_0 = 4167525.0 for ii, l_arr in enumerate(line_arr[:-1]): lat = float(l_arr[7]) lon = float(l_arr[8]) depth = float(l_arr[9]) mag[ii] = float(l_arr[10]) zone, east, north = ll2utm.LLtoUTM(23, lat, lon) x[ii] = (east - east_0) / 1000. y[ii] = (north - north_0) / 1000. z[ii] = depth + 3 a2vtk.pointsToVTK( r"C:\Users\jpeacock\Documents\LV\lv_3d_models\2013_lin_relocated_eq", y, x, z, data={ 'depth': z, 'magnitude': mag })
llen = len(lines) #Make vectors for input into vtk program Tomovals = np.zeros(llen) Radii = np.zeros(llen) Colat = np.zeros(llen) Lon = np.zeros(llen) i=0 for line in lines: vals = line.split(' ') R = float(vals[0]) lat = float(vals[2]) lon = float(vals[1]) tomoval = float(vals[3]) #this is going to be in anomaly value #Write to ASPECT input r,rlon,rlat = converttoASPECT(R,lon,lat) Radii[i] = r Colat[i] = rlat Lon[i] = rlon Tomovals[i] = tomoval i+=1 Xnew,Ynew,Znew = spheretocart(Lon,Colat,Radii) pointsToVTK("./TempTomoTestSVJ",Xnew,Ynew,Znew,data = {"Pertb": Tomovals})
all_particles = data_file['all_particles'] all_weights = data_file['all_weights'] all_est = data_file['all_est'] all_true = data_file['all_true'] all_particles_t = np.zeros((all_particles.shape[0], all_particles.shape[1], 3)) all_particles_t[:, :, 0:2] = all_particles*100 for t in range(all_particles.shape[0]): all_particles_t[t, :, 2] = t xs = all_particles_t[:, :, 0].flatten() ys = all_particles_t[:, :, 1].flatten() zs = all_particles_t[:, :, 2].flatten() ws = all_weights.flatten() eh.pointsToVTK('./particle_data', xs, ys, zs, data={"weights": ws}) all_particles_t = np.zeros((all_particles.shape[0], all_particles.shape[1], 3)) all_particles_t[:, :, 0:2] = all_particles*100 for t in range(all_particles.shape[0]): all_particles_t[t, :, 2] = t all_particles_t[t, : , 0:2] = np.subtract(all_particles_t[t, :, 0:2], all_true[t,:]*100) xs = all_particles_t[:, :, 0].flatten() ys = all_particles_t[:, :, 1].flatten() zs = all_particles_t[:, :, 2].flatten() ws = all_weights.flatten() eh.pointsToVTK('./particle_minus_true_data', xs, ys, zs, data = {'weights': ws})
# * EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * # * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * # * BUT NOT LIMITED TO, PROCUREMEN OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * # * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * # * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * # * 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 pointsToVTK function. * # ************************************************************** from evtk.hl import pointsToVTK import numpy as np # Example 1 npoints = 100 x = np.random.rand(npoints) y = np.random.rand(npoints) z = np.random.rand(npoints) pressure = np.random.rand(npoints) temp = np.random.rand(npoints) pointsToVTK("./rnd_points", x, y, z, data={"temp": temp, "pressure": pressure}) # Example 2 x = np.arange(1.0, 10.0, 0.1) y = np.arange(1.0, 10.0, 0.1) z = np.arange(1.0, 10.0, 0.1) pointsToVTK("./line_points", x, y, z, data={"elev": z})
# east_0 = 334460.00 # north_0 = 4173370.00 # east_0 = 336720. # north_0 = 4167510.0 east_0 = 336720.0 north_0 = 4167510.0 while read_line < len_file: sline = sfid.readline() slst = sline.strip().split() lat = float(slst[6]) lon = float(slst[7]) depth = float(slst[8]) zone, east, north = utm2ll.LLtoUTM(23, lat, lon) x[read_line] = (east - east_0) / 1000.0 y[read_line] = (north - north_0) / 1000.0 z[read_line] = depth read_line += 1 sfid.close() pointsToVTK( r"c:\Users\jpeacock\Documents\LV\lv_3d_models\lv_2014_swarm_locations_lvc", y, x, z, data={"depth": z}, )
def dump( self, matlist, idx, dw ): fName = self.fname + str(idx).zfill(self.nzeros) fNodeName = self.fname + 'nodes_' + str(idx).zfill(self.nzeros) # Standard Save x = []; y = []; v = []; ms = []; matid = [] for mat in matlist: dwi = mat.dwi px,pv,pVS,pVol = dw.getMult( ['px','pxI','pVS','pVol'], dwi ) nn = len(pVol) matid += [dwi]*nn x += list(px[:,0]) y += list(px[:,1]) vx = pv[:,0] vy = pv[:,1] v += list( np.sqrt( vx*vx + vy*vy ) * np.sign(vx) ) pS = [pVS[ii]/pVol[ii] for ii in range(nn)] ms += [vonMises(pp) for pp in pS] x = np.array(x) y = np.array(y) z = np.zeros(x.shape) v = np.array(v) ms = np.array(ms) matid = np.array(matid) pdat = {"vonMises":ms, "v":v, "mat":matid} # Create Node Grid gX = dw.get('gx',matlist[0].dwi) gx = np.array(gX[:,0]) gy = np.array(gX[:,1]) gz = np.zeros(gx.shape) gdat = {"g_test":gz} partList = ['pX','pxI','pvI','pw','pfi','pfe','pfc','pwc','pn'] nodeList = ['gv','gw','ga','gfe','gfi','gn','gfc','gwc','gDist','gm'] for var in partList: tmp1 = [] tmp2 = [] tmp3 = [] for mat in matlist: dwi = mat.dwi pvar = dw.get( var, dwi ) tmp1 += list(pvar[:,0]) tmp2 += list(pvar[:,1]) tmp3 += list(vnorm(pvar)) pdat[var+'_x'] = np.array(tmp1) pdat[var+'_y'] = np.array(tmp2) pdat[var] = np.array(tmp3) for var in nodeList: for mat in matlist: dwi = mat.dwi gvar = dw.get( var, dwi ) try: gdat[var+str(dwi)+'_x'] = np.array(list(gvar[:,0])) gdat[var+str(dwi)+'_y'] = np.array(list(gvar[:,1])) gdat[var+str(dwi)] = vnorm(gvar) except Exception: gdat[var+str(dwi)] = gvar pointsToVTK(fName, x, y, z, data = pdat) pointsToVTK(fNodeName, gx, gy, gz, data = gdat)
################################################################## dist_names = subprocess.check_output("ls *.bin", shell=True).split() for dist_name in dist_names: cell_name = dist_name.split('_')[0] mesh_name = cell_name + 'm_HARMONIC_100p.msh' print print '*** ' + cell_name + ' ***' print 'reading mesh file: ' + mesh_name x,y,z = cs.get_mesh_coords(mesh_name) print 'reading data file: ' + dist_name dist = cs.get_data(dist_name) # get start and finish indices for a single cycle i_start = 0 i_finish = dist.shape[1] # write vtk time series files if os.path.isdir(cell_name): os.system("rm -rf " + cell_name) os.mkdir(cell_name) print 'creating vtk files...' for i in xrange(i_start, i_finish, 1): d = {} d["c"] = dist[:, i] fname = cell_name + '/' + cell_name + '_' + str(i).zfill(4) pointsToVTK(fname, x, y, z, data = d) print 'max =', '{:0.3f}'.format(dist.max())
lines = sfid.readlines() x = np.zeros(len_file) y = np.zeros(len_file) z = np.zeros(len_file) read_line = 0 east_0 = 336800.00 north_0 = 4167510.00 for sline in lines[14:]: slst = sline.strip().split() lat = float(slst[6]) lon = float(slst[7]) depth = float(slst[8]) zone, east, north = utm2ll.LLtoUTM(23, lat, lon) x[read_line] = (east-east_0)/1000. y[read_line] = (north-north_0)/1000. z[read_line] = depth read_line += 1 sfid.close() pointsToVTK(r"c:\Users\jpeacock\Documents\LV\lv_3d_models\shelly_2015_mm_eq_lcv", y, x, z, data={'depth':z})
s_array = s_array[np.where((s_array["lon"] >= -119.25) & (s_array["lon"] <= -118.7))] # print east_0, north_0 east = np.zeros(s_array.shape[0]) north = np.zeros(s_array.shape[0]) depth = [] mag = [] for ii, ss in enumerate(s_array): ee, nn, zz = gis_tools.project_point_ll2utm(ss["lat"], ss["lon"]) east[ii] = (ee - east_0) / 1000.0 north[ii] = (nn - north_0) / 1000.0 x = north.copy() y = east.copy() z = s_array["depth"].copy() mag = s_array["mag"].copy() pointsToVTK( r"c:\Users\jpeacock\Documents\MonoBasin\EQ_DD_locations_mlc", x, y, z, data={ "mag": mag, "depth": z }, )
for line in lines: vals = line.split() radf = float(vals[0]) latf = 90-float(vals[2]) lonf = float(vals[1]) tomof = float(vals[3]) if (lat==latf): tmpX.append(lonf*(np.pi/180.0)) tmpY.append(latf*(np.pi/180.0)) tmpZ.append(radf) tmpData.append(tomof) #Previous, crude estimation of the temperature #Temporary for december test: Convert to temperature in a crude fashion. Need to link this to a geothermal profile at some point #tomotemp = (1600 - ((tomof/100.0)*0.25)/1e-4) #if tomotemp < 1300: # tomotemp = 1300 #if tomotemp > 1800: # tomotemp = 1700 outfile.write('%g %g %g %g\n' %(radf,lonf*(np.pi/180),latf*(np.pi/180),tomof)) print 'Done %g' %i i+=1 #Make a point cloud file containing the full grid X,Y,Z = spheretocart(np.array(tmpX),np.array(tmpY),np.array(tmpZ)) pointsToVTK("./ASPECT_GlobeTomo_input",X,Y,Z,data = {"Pertb": np.array(tmpData)})
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)
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)
#--------------------------------------------------- #eq_fn = r"/mnt/hgfs/jpeacock/Documents/Geothermal/Washington/MSH/mshn_earthquake_locations_ll.csv" eq_fn = r"c:\Users\jpeacock\Documents\Geothermal\Washington\eq_psns_all_msh.csv" sv_path = os.path.dirname(eq_fn) #-------------------------------------- eq_df = pd.read_csv(eq_fn) # model center #east_0 = 555703.-253 #north_0 = 5132626.0+26 east_0 = 562012. north_0 = 5128858. x = np.zeros_like(eq_df.Lat) y = np.zeros_like(eq_df.Lon) for lat, lon, index in zip(eq_df.Lat, eq_df.Lon, range(x.size)): east, north, zone = gis_tools.project_point_ll2utm(lat, lon) x[index] = (east - east_0) / 1000. y[index] = (north - north_0) / 1000. pointsToVTK(eq_fn[:-4] + 'shz', y, x, np.array(eq_df.Depth), data={ 'depth': np.array(eq_df.Depth), 'magnitude': np.array(eq_df.Magnitude) })
lines = ['lat,lon,east,north,depth,mag'] easting = np.zeros(lp_arr.size) northing = np.zeros(lp_arr.size) for kk, lp in enumerate(lp_arr): east, north, zone = gis_tools.project_point_ll2utm(float(lp['lat']), float(lp['lon'])) lines.append(','.join([ '{0:.5f}'.format(ii) for ii in [lp['lat'], lp['lon'], east, north, lp['depth'], lp['mag']] ])) easting[kk] = east northing[kk] = north with open(fn[:-4] + '_ew.txt', 'w') as fid: fid.write('\n'.join(lines)) # write vtk file #pointsToVTK(fn[0:-4], # (northing-5144510)/1000., # (easting-573840)/1000., # lp_arr['depth'], # data={'depth':lp_arr['depth'], 'mag':lp_arr['mag']}) # # write vtk file shear zone pointsToVTK(fn[0:-4] + '_shz', (northing - 5128858.) / 1000., (easting - 562012.) / 1000., lp_arr['depth'], data={ 'depth': lp_arr['depth'], 'mag': lp_arr['mag'] })
# vxs = vx[ini:fin] # vys = vy[ini:fin] # "Vx" : vxs, "Vy" : vys vel = (vx[ini:fin], vy[ini:fin], np.zeros(fin - ini)) tipos = tipo[ini:fin] rsols = rsol[ini:fin] nIDs = nID[ini:fin] thetas = theta[ini:fin] omegas = omega[ini:fin] if np.isnan([theta[ini]]) or grupoquegira != grupo: pointsToVTK(via + '/' + folder + '/grupo' + str(grupo) + '_' + str(fnum + aux1), xs, ys, zs, data={ "Vel": vel, "Tipo": tipos, "raio_solido": rsols, "nID": nIDs }) else: pointsToVTK(via + '/' + folder + '/grupo' + str(grupo) + '_' + str(fnum + aux1), xs, ys, zs, data={ "Vel": vel, "Theta": thetas, "Omega": omegas,
def dump(self, matlist, idx, dw): fName = self.fname + str(idx).zfill(self.nzeros) fNodeName = self.fname + 'nodes_' + str(idx).zfill(self.nzeros) # Standard Save x = [] y = [] v = [] ms = [] matid = [] for mat in matlist: dwi = mat.dwi px, pv, pVS, pVol = dw.getMult(['px', 'pxI', 'pVS', 'pVol'], dwi) nn = len(pVol) matid += [dwi] * nn x += list(px[:, 0]) y += list(px[:, 1]) vx = pv[:, 0] vy = pv[:, 1] v += list(np.sqrt(vx * vx + vy * vy) * np.sign(vx)) pS = [pVS[ii] / pVol[ii] for ii in range(nn)] ms += [vonMises(pp) for pp in pS] x = np.array(x) y = np.array(y) z = np.zeros(x.shape) v = np.array(v) ms = np.array(ms) matid = np.array(matid) pdat = {"vonMises": ms, "v": v, "mat": matid} # Create Node Grid gX = dw.get('gx', matlist[0].dwi) gx = np.array(gX[:, 0]) gy = np.array(gX[:, 1]) gz = np.zeros(gx.shape) gdat = {"g_test": gz} partList = ['pX', 'pxI', 'pvI', 'pw', 'pfi', 'pfe', 'pfc', 'pwc', 'pn'] nodeList = [ 'gv', 'gw', 'ga', 'gfe', 'gfi', 'gn', 'gfc', 'gwc', 'gDist', 'gm' ] for var in partList: tmp1 = [] tmp2 = [] tmp3 = [] for mat in matlist: dwi = mat.dwi pvar = dw.get(var, dwi) tmp1 += list(pvar[:, 0]) tmp2 += list(pvar[:, 1]) tmp3 += list(vnorm(pvar)) pdat[var + '_x'] = np.array(tmp1) pdat[var + '_y'] = np.array(tmp2) pdat[var] = np.array(tmp3) for var in nodeList: for mat in matlist: dwi = mat.dwi gvar = dw.get(var, dwi) try: gdat[var + str(dwi) + '_x'] = np.array(list(gvar[:, 0])) gdat[var + str(dwi) + '_y'] = np.array(list(gvar[:, 1])) gdat[var + str(dwi)] = vnorm(gvar) except Exception: gdat[var + str(dwi)] = gvar pointsToVTK(fName, x, y, z, data=pdat) pointsToVTK(fNodeName, gx, gy, gz, data=gdat)
args=cmdparser.parse_args() from CaseSettings import CaseSettings conf = CaseSettings(args.config) if args.times is None: args.times = conf.getTimes() try: _ = iter(args.times) except TypeError: args.times = [args.times] import numpy from evtk.hl import pointsToVTK x = numpy.loadtxt("%s.x.txt" % conf.basename, usecols=[1], skiprows=1) y = numpy.loadtxt("%s.y.txt" % conf.basename, usecols=[1], skiprows=1) for time in [t[0] for t in args.times]: data = {} for v in conf.getVariables(): d = numpy.loadtxt("%s.var%d.t%d.txt" % (conf.basename, v[0], time), usecols=[1]) data[v[1]] = d if conf.mode == 2: z = numpy.zeros_like(x) elif conf.mode == 3: z = numpy.loadtxt("%s.var%d.t%d.txt" % (conf.basename, conf.z, time), usecols=[1]) pointsToVTK("%s/%s-%s.t%d" % (conf.outputpath, conf.basefilename, args.suffix, time), x, y, z, data=data)