def clip_modem_model(model_fn, clip): """ Read in ModEM model and clip to a smaller box """ m_obj = modem.Model() m_obj.read_model_file(model_fn) ### --> need to convert model coordinates into lat and lon utm_center = gis_tools.project_point_ll2utm(model_center[1], model_center[0]) lat = np.zeros_like(m_obj.grid_north[clip:-(clip + 1)]) lon = np.zeros_like(m_obj.grid_east[clip:-(clip + 1)]) depth = m_obj.grid_z[:-1] / 1000.0 for ii, north in enumerate(m_obj.grid_north[clip:-(clip + 1)]): m_lat, m_lon = gis_tools.project_point_utm2ll(utm_center[0], utm_center[1] + north, utm_center[2]) lat[ii] = m_lat for ii, east in enumerate(m_obj.grid_east[clip:-(clip + 1)]): m_lat, m_lon = gis_tools.project_point_utm2ll(utm_center[0] + east, utm_center[1], utm_center[2]) lon[ii] = m_lon res = np.log10(m_obj.res_model[clip:-clip, clip:-clip, :]) return lat, lon, depth, res
def test_project_point_ll2utm(self): easting, northing, zone = project_point_ll2utm(self.lat, self.lon) print(zone, easting, northing) self.assertTrue(zone == self.zone) self.assertTrue(np.isclose(easting, self.easting)) self.assertTrue(np.isclose(northing, self.northing))
def get_station_locations(self, input_list): """ get station locations from a list of edi files Arguments ------------- **input_list** : list list of edi file names, or mt_objects Returns ------------ * fills station_locations array """ # print input_list mt_obj_list = self._get_mt_objs_from_list(input_list) # if station locations are not input read from the edi files if mt_obj_list is None: raise AttributeError( 'mt_obj_list is None, need to input a list of ' 'mt objects to read in.') n_stations = len(mt_obj_list) if n_stations == 0: raise ModEMError('No .edi files in edi_list, please check ' 'file locations.') # make a structured array to put station location information into self.station_locations = np.zeros(n_stations, dtype=self.dtype) # get station locations in meters for ii, mt_obj in enumerate(mt_obj_list): self.station_locations[ii]['lat'] = mt_obj.lat self.station_locations[ii]['lon'] = mt_obj.lon self.station_locations[ii]['station'] = mt_obj.station self.station_locations[ii]['elev'] = mt_obj.elev if (self.model_epsg is not None) or (self.model_utm_zone is not None): east, north, utm_zone = gis_tools.project_point_ll2utm( mt_obj.lat, mt_obj.lon, utm_zone=self.model_utm_zone, epsg=self.model_epsg) self.station_locations[ii]['east'] = east self.station_locations[ii]['north'] = north self.station_locations[ii]['zone'] = utm_zone else: self.station_locations[ii]['east'] = mt_obj.east self.station_locations[ii]['north'] = mt_obj.north self.station_locations[ii]['zone'] = mt_obj.utm_zone # get relative station locations self.calculate_rel_locations()
def test_project_point_ll2utm(self): easting, northing, zone = gis_tools.project_point_ll2utm(self.lat_d, self.lon_d) if isinstance(zone, (np.bytes_, bytes)): zone = zone.decode('UTF-8') self.assertTrue(zone == self.zone) self.assertTrue(np.isclose(easting, self.easting)) self.assertTrue(np.isclose(northing, self.northing))
def test_project_point_ll2utm(self): easting, northing, zone = project_point_ll2utm(self.lat, self.lon) print((zone, easting, northing)) if isinstance(zone, np.bytes_): utm_zone = zone.decode('UTF-8') self.assertTrue(utm_zone == self.zone) self.assertTrue(np.isclose(easting, self.easting)) self.assertTrue(np.isclose(northing, self.northing))
def get_model_lower_left_coord(self, model_fn=None, model_center=None, pad_east=0, pad_north=0): """ Find the models lower left hand corner in (lon, lat) decimal degrees """ if model_fn is not None: self.model_fn = model_fn if self.model_fn is None: raise IOError('Need to input a ModEM model file name to read in') self.pad_east = pad_east self.pad_north = pad_north model_obj = modem.Model() model_obj.model_fn = self.model_fn model_obj.read_model_file() if model_center: center_zone, center_east, center_north = gis_tools.project_point_ll2utm( model_center[1], model_center[0]) lower_left_east = center_east+model_obj.grid_center[1]+\ model_obj.nodes_east[0:pad_east].sum()-\ model_obj.nodes_east[pad_east]/2 lower_left_north = center_north+model_obj.grid_center[1]+\ model_obj.nodes_north[0:pad_north].sum()+\ model_obj.nodes_north[pad_north]/2 ll_lat, ll_lon = gis_tools.project_point_utm2ll( lower_left_north, lower_left_east, center_zone) print 'Lower Left Coordinates should be ({0:.5f}, {1:.5f})'.format( ll_lon, ll_lat) return (ll_lon, ll_lat) else: raise IOError('Need to input model center (lon, lat)')
#mfn = r"c:\Users\jpeacock\Documents\Geothermal\GraniteSprings\modem_inv\inv_02_tip\gs_prm_err03_tip02_cov03_NLCG_129.rho" mfn = r"c:\Users\jpeacock\Documents\Geothermal\GabbsValley\modem_inv\inv_02\gv_z03_t03_c02__NLCG_118.rho" dfn = r"c:\Users\jpeacock\Documents\Geothermal\GabbsValley\modem_inv\inv_02\gv_modem_data_ef07_tip02.dat" save_root = 'gv' rot_angle = 0.0 #--> read model file mod_obj = modem.Model() mod_obj.read_model_file(mfn) #--> get center position #model_center = (40.227213, -118.927443) model_center = (38.772697, -118.149196) c_east, c_north, c_zone = gis_tools.project_point_ll2utm(model_center[0], model_center[1], epsg=26911) #--> set padding east_pad = 4 north_pad = 4 z_pad = np.where(mod_obj.grid_z > 30000)[0][0] cos_ang = np.cos(np.deg2rad(rot_angle)) sin_ang = np.sin(np.deg2rad(rot_angle)) rot_matrix = np.matrix(np.array([[cos_ang, sin_ang], [-sin_ang, cos_ang]])) #--> write model xyz file lines = [ '# model_type = electrical resistivity', '# model_location = Gabbs Valley, NV', '# model_author = J Peacock',
# mfn = r"c:\Users\jpeacock\OneDrive - DOI\Geothermal\Umatilla\modem_inv\inv_09\um_z05_c05_089.rho" mfn = r"c:\Users\jpeacock\OneDrive - DOI\Geothermal\Umatilla\modem_inv\inv_09\um_z05_c025_086.rho" surface_fn = r"c:\Users\jpeacock\OneDrive - DOI\General - Umatilla\2&3D modeling\exported_3D_surfaces\for_Jared\csvFiles\dem_toPts2.csv" prebase_fn = r"c:\Users\jpeacock\OneDrive - DOI\General - Umatilla\2&3D modeling\exported_3D_surfaces\for_Jared\csvFiles\preBase_toPts2.csv" precrb_fn = r"c:\Users\jpeacock\OneDrive - DOI\General - Umatilla\2&3D modeling\exported_3D_surfaces\for_Jared\csvFiles\preCRB_toPts2.csv" # model center for inv_09 model_center = (45.654713, -118.547148) # model center for inv_06 # model_center = (45.650594, -118.562997) m_epsg = 26911 m_east, m_north, m_zone = gis_tools.project_point_ll2utm(model_center[0], model_center[1], epsg=m_epsg) def interp(model_east, model_north, surface_east, surface_north, surface_values): xg, yg = np.meshgrid(surface_east, surface_north) mxg, myg = np.meshgrid(model_east, model_north) points = np.vstack([arr.flatten() for arr in [xg, yg]]).T values = surface_values.flatten() xi = np.vstack([arr.flatten() for arr in [mxg, myg]]).T return interpolate.griddata(points, values, xi).reshape(mxg.shape) def read(fn):
mfn_shz = r"c:\Users\jpeacock\Documents\iMush\modem_inv\shz_inv_02\shz_smt_z04_t03_c02_NLCG_070.rho" modem_data = modem.Data() modem_data.read_data_file(dfn) modem_imush = modem.Model() modem_imush.read_model_file(mfn_imush) modem_shz = modem.Model() modem_shz.read_model_file(mfn_shz) imush_center = (46.450149, -122.032858) shz_center = (46.310461, -122.194629) imush_east, imush_north, zone = gis_tools.project_point_ll2utm( imush_center[0], imush_center[1] ) shz_east, shz_north, zone = gis_tools.project_point_ll2utm(shz_center[0], shz_center[1]) d_east = imush_east - shz_east + 8500 d_north = imush_north - shz_north + 8000 imush_res = interp_grid( modem_imush, modem_shz, shift_east=d_east, shift_north=d_north, smooth_kernel=1, pad=3, )
# s_array = s_array[np.where((s_array['lon'] >= -122.92) & (s_array['lon']<=-122.72))] # make a new array with easting and northing vtk_arr = np.zeros( df.shape[0], dtype=[ ("east", np.float), ("north", np.float), ("depth", np.float), ("mag", np.float), ], ) # 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"] }, )
""" Created on Wed Oct 25 15:05:19 2017 @author: jrpeacock """ import netCDF4 import mtpy.modeling.modem as modem import mtpy.utils.gis_tools as gis_tools import numpy as np mfn = r"c:\Users\jpeacock\OneDrive - DOI\Geothermal\Umatilla\modem_inv\inv_09\um_z05_c025_086.rho" model_center = (45.654713, -118.547148) model_center_ne = gis_tools.project_point_ll2utm( model_center[0], model_center[1], epsg=26911 ) m_obj = modem.Model() m_obj.read_model_file(mfn) # need to make a lat and lon list lat = np.zeros(m_obj.nodes_north.size) lon = np.zeros(m_obj.nodes_east.size) for ii, north in enumerate(model_center_ne[0] - m_obj.grid_north[:-1]): lat_00, lon_00 = gis_tools.project_point_utm2ll( north, model_center_ne[1], model_center_ne[2] ) lat[ii] = lat_00
from evtk.hl import pointsToVTK import numpy as np from mtpy.utils import gis_tools #--------------------------------------------------- #sfn = r"c:\Users\jpeacock\Documents\LVEarthquakeLocations_lldm.csv" sfn = r"c:\Users\jpeacock\Documents\MonoBasin\EQ_DD_locations.csv" #save_sfn = sfn[:-4]+'_lldm.csv' #sfid = file(save_sfn, 'w') #sfid.writelines(line_list) #sfid.close() model_center = (37.949138, -118.951690) east_0, north_0, zone_0 = gis_tools.project_point_ll2utm( model_center[0], model_center[1]) #east_0 = 336800. #north_0 = 4167510.0 #east_0 = 337350.-1200 #north_0 = 4178250.0 s_array = np.loadtxt(sfn, delimiter=',', dtype=[('lat', np.float), ('lon', np.float), ('depth', np.float), ('mag', np.float)], skiprows=78, usecols=(1, 2, 3, 8)) #zone0, east_0, north_0 = utm2ll.LLtoUTM(23, s_array['lat'].mean(), # s_array['lon'].mean())
gdf = gpd.GeoDataFrame(df) gdf.crs = {"init": "epsg:4326"} gdf.to_file(fn[:-4] + ".shp") ### Make vtk of earthquakes # model_east, model_north, model_utm = gis_tools.project_point_ll2utm( # 39.556431, -119.800694 # ) # Umatilla # model_east, model_north, model_utm = gis_tools.project_point_ll2utm( # 45.650594, -118.562997 # ) # Clear Lake model_east, model_north, model_utm = gis_tools.project_point_ll2utm( 38.987645, -122.751369) # make a new array with easting and northing vtk_arr = np.zeros( df.shape[0], dtype=[ ("east", np.float), ("north", np.float), ("depth", np.float), ("mag", np.float), ], ) # compute easting and northing for ii in range(df.shape[0]): e, n, z = gis_tools.project_point_ll2utm(df.latitude.iloc[ii],
def array2raster(raster_fn, origin, cell_width, cell_height, res_array, projection='WGS84', rotation_angle=0.0): """ converts an array into a raster file that can be read into a GIS program. Arguments: -------------- **raster_fn** : string full path to save raster file to **origin** : (lon, lat) longitude and latitude of southwest corner of the array **cell_width** : float (in meters) size of model cells in east-west direction **cell_height** : float (in meters) size of model cells in north-south direction **res_array** : np.ndarray(east, north) resistivity array in linear scale. **projection** : string name of the projection datum **rotation_angle** : float angle in degrees to rotate grid. Assuming N = 0 and E = 90, positive clockwise Output: ---------- * creates a geotiff file projected into projection in UTM. The values are in log scale for coloring purposes. """ # convert rotation angle to radians r_theta = np.deg2rad(rotation_angle) res_array = np.flipud(res_array[::-1]) ncols = res_array.shape[1] nrows = res_array.shape[0] utm_point = gis_tools.project_point_ll2utm(origin[1], origin[0], datum=projection) origin_east = utm_point[0] origin_north = utm_point[1] utm_zone = utm_point[2] # set drive to make a geo tiff driver = gdal.GetDriverByName('GTiff') # make a raster with the shape of the array to be written out_raster = driver.Create(raster_fn, ncols, nrows, 1, gdal.GDT_Float32) # geotransform: # GeoTransform[0] = top left x # GeoTransform[1] = w-e pixel resolution # GeoTransform[2] = rotation, 0 if image is "north up" # GeoTransform[3] = top left y # GeoTransform[4] = rotation, 0 if image is "north up" # GeoTransform[5] = n-s pixel resolution # padfTransform[0] = corner lon # padfTransform[1] = cos(alpha)*(scaling) # padfTransform[2] = -sin(alpha)*(scaling) # padfTransform[3] = corner lat # padfTransform[4] = sin(alpha)*(scaling) # padfTransform[5] = cos(alpha)*(scaling) out_raster.SetGeoTransform( (origin_east, np.cos(r_theta) * cell_width, -np.sin(r_theta) * cell_width, origin_north, np.sin(r_theta) * cell_height, np.cos(r_theta) * cell_height)) # create a band for the raster data to be put in outband = out_raster.GetRasterBand(1) outband.WriteArray(res_array) # geo reference the raster #out_raster_georef = osr.SpatialReference() #out_raster_georef.ImportFromEPSG(4326) utm_cs = osr.SpatialReference() zone_number = int(utm_zone[0:-1]) is_northern = True if utm_zone[-1].lower() > 'n' else False utm_cs.SetUTM(zone_number, is_northern) out_raster.SetProjection(utm_cs.ExportToWkt()) # be sure to flush the data outband.FlushCache()
model_fn = r"c:\Users\jpeacock\Documents\imush\Z4T3_cov0p2x2_L1E2_NLCG_061.rho" save_fn = r"c:\Users\jpeacock\Documents\imush\bedrosian_imush_mt_2018_log10_clip_iris.nc" model_center = ( -122.080378, 46.387827, ) clip = 14 iris_submit = True # ============================================================================= # Read in model file # ============================================================================= m_obj = modem.Model() m_obj.read_model_file(model_fn) ### --> need to convert model coordinates into lat and lon utm_center = gis_tools.project_point_ll2utm(model_center[1], model_center[0]) lat = np.zeros_like(m_obj.grid_north[clip:-(clip + 1)]) lon = np.zeros_like(m_obj.grid_east[clip:-(clip + 1)]) depth = m_obj.grid_z[:-1] / 1000. for ii, north in enumerate(m_obj.grid_north[clip:-(clip + 1)]): m_lat, m_lon = gis_tools.project_point_utm2ll(utm_center[0], utm_center[1] + north, utm_center[2]) lat[ii] = m_lat for ii, east in enumerate(m_obj.grid_east[clip:-(clip + 1)]): m_lat, m_lon = gis_tools.project_point_utm2ll(utm_center[0] + east, utm_center[1], utm_center[2]) lon[ii] = m_lon
def interpolate_elevation_to_grid(grid_east, grid_north, epsg=None, utm_zone=None, surfacefile=None, surface=None, method='linear', fast=True): """ # Note: this documentation is outdated and seems to be copied from # model.interpolate_elevation2. It needs to be updated. This # funciton does not update a dictionary but returns an array of # elevation data. project a surface to the model grid and add resulting elevation data to a dictionary called surface_dict. Assumes the surface is in lat/long coordinates (wgs84) The 'fast' method extracts a subset of the elevation data that falls within the mesh-bounds and interpolates them onto mesh nodes. This approach significantly speeds up (~ x5) the interpolation procedure. **returns** nothing returned, but surface data are added to surface_dict under the key given by surfacename. **inputs** choose to provide either surface_file (path to file) or surface (tuple). If both are provided then surface tuple takes priority. surface elevations are positive up, and relative to sea level. surface file format is: ncols 3601 nrows 3601 xllcorner -119.00013888889 (longitude of lower left) yllcorner 36.999861111111 (latitude of lower left) cellsize 0.00027777777777778 NODATA_value -9999 elevation data W --> E N | V S Alternatively, provide a tuple with: (lon,lat,elevation) where elevation is a 2D array (shape (ny,nx)) containing elevation points (order S -> N, W -> E) and lon, lat are either 1D arrays containing list of longitudes and latitudes (in the case of a regular grid) or 2D arrays with same shape as elevation array containing longitude and latitude of each point. other inputs: surfacename = name of surface for putting into dictionary surface_epsg = epsg number of input surface, default is 4326 for lat/lon(wgs84) method = interpolation method. Default is 'nearest', if model grid is dense compared to surface points then choose 'linear' or 'cubic' """ # read the surface data in from ascii if surface not provided if surfacefile: lon, lat, elev = mtfh.read_surface_ascii(surfacefile) elif surface: lon, lat, elev = surface else: raise ValueError("'surfacefile' or 'surface' must be provided") # if lat/lon provided as a 1D list, convert to a 2d grid of points if len(lon.shape) == 1: # BM: There seems to be an issue using dense grids (X and Y # become arrays of (N, N)), and get flattened to 1D array # of N^2 in point projection below. # Interpolation then can't be performed because # there's a dimension mismatch between lon/lat and elev. # This issue doesn't happen when using 'fast' method below, so # when not using fast, get a sparse grid instead. if fast: lon, lat = np.meshgrid(lon, lat) else: lon, lat = np.meshgrid(lon, lat, sparse=True) lat = lat.T if len(grid_east.shape) == 1: grid_east, grid_north = np.meshgrid(grid_east, grid_north) if (fast): buffer = 1 # use a buffer of 1 degree around mesh-bounds mlatmin, mlonmin = gis_tools.project_point_utm2ll(grid_east.min(), grid_north.min(), epsg=epsg, utm_zone=utm_zone) mlatmax, mlonmax = gis_tools.project_point_utm2ll(grid_east.max(), grid_north.max(), epsg=epsg, utm_zone=utm_zone) subsetIndices = (lon >= mlonmin - buffer) & \ (lon <= mlonmax + buffer) & \ (lat >= mlatmin - buffer) & \ (lat <= mlatmax + buffer) lon = lon[subsetIndices] lat = lat[subsetIndices] elev = elev[subsetIndices] # end if projected_points = gis_tools.project_point_ll2utm(lat, lon, epsg=epsg, utm_zone=utm_zone) # elevation in model grid # first, get lat,lon points of surface grid points = np.vstack([ arr.flatten() for arr in [projected_points.easting, projected_points.northing] ]).T # corresponding surface elevation points values = elev.flatten() # xi, the model grid points to interpolate to xi = np.vstack([arr.flatten() for arr in [grid_east, grid_north]]).T # elevation on the centre of the grid nodes elev_mg = spi.griddata(points, values, xi, method=method).reshape(grid_north.shape) return elev_mg
def northing(self): e, n, z = gis_tools.project_point_ll2utm(self.lat, self.lon) return n
lp_arr = np.loadtxt( fn, delimiter=",", skiprows=1, usecols=[0, 1, 2, 3], dtype={ "names": ("lat", "lon", "depth", "mag"), "formats": (np.float, np.float, np.float, np.float), }, ) 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'],
delimiter=',', dtype=[('lat', np.float), ('lon', np.float), ('depth', np.float), ('mag', np.float)], skiprows=14, usecols=(1, 2, 3, 4)) # 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,
import mtpy.modeling.modem as modem import mtpy.utils.gis_tools as gis_tools import numpy as np import matplotlib.pyplot as plt mfn = ( r"c:\Users\jpeacock\Documents\ClearLake\modem_inv\inv03\gz_err03_cov02_NLCG_057.rho" ) dfn = ( r"c:\Users\jpeacock\Documents\ClearLake\modem_inv\inv03\gz_data_err03_tec_edit.dat" ) model_center = (38.831979, -122.828190) model_center_proj = gis_tools.project_point_ll2utm(model_center[0], model_center[1], epsg=26742) m_obj = modem.Model() m_obj.read_model_file(mfn) clip = 6 m_to_feet = 3.280839895 # need to center the location, which is in the nodes east = m_obj.nodes_east[clip:-clip + 1] * m_to_feet north = m_obj.nodes_north[clip:-clip + 1] * m_to_feet z = m_obj.nodes_z[0:-clip] * m_to_feet res = m_obj.res_model[clip:-clip + 1, clip:-clip + 1, 0:-clip + 1]
num=(north.max() - north.min()) / d) xg, yg = np.meshgrid(x_new, y_new) ### interpolate the data onto a regular grid basement = interpolate.griddata((east, north), -1 * a[2], (xg, yg), method='cubic') ### make raster b = array2raster.array2raster(fn[:-4] + '.tif', (lower_left[1], lower_left[0]), d, d, basement) ### make a point cloud x0, y0, z0 = gis_tools.project_point_ll2utm(model_center[0], model_center[1], epsg=data_epsg) x = (north.copy() - y0) / 1000. y = (east.copy() - x0) / 1000. z = -1 * a[2].copy() pointsToVTK(fn[0:-4], x, y, z, {'depth': z}) fig = plt.figure(2) fig.clf() ax = fig.add_subplot(1, 1, 1, aspect='equal') im = ax.pcolormesh(xg, yg, basement, cmap='viridis', vmin=0, vmax=3.00) plt.colorbar(mappable=im, ax=ax) if dfn is not None: for lat, lon in zip(d_obj.station_locations.lat,
# ============================================================================= from evtk.hl import pointsToVTK import numpy as np import mtpy.utils.gis_tools as gis_tools import simplekml as skml import pandas as pd import geopandas as gpd from shapely.geometry import Point # ============================================================================= # Parameters # ============================================================================= sfn = r"c:\Users\jpeacock\Documents\MountainPass\MusicValley\mv_scec_eq_catalog.txt" model_center = (33.992818, -116.009367) model_east, model_north, model_zone = gis_tools.project_point_ll2utm( model_center[0], model_center[1]) df = pd.read_csv(sfn, sep='\s+', skiprows=2, skipfooter=4, index_col=False) df.columns = df.columns.str.lower() # make a new array with easting and northing vtk_arr = np.zeros(df.shape[0], dtype=[('east', np.float), ('north', np.float), ('depth', np.float), ('mag', np.float)]) # 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_east) / 1000. vtk_arr[ii]['north'] = (n - model_north) / 1000. vtk_arr[ii]['depth'] = df.depth[ii]
#--------------------------------------------------- #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) })
# 'vs_depth_slices', # '{0:02}_vs.tif'.format(ii, z[ii])), # (v['lon'].min(), v['lat'].min()), # dx*1000, # dy*1000, # vs_arr[:, :, ii]) # a2r.array2raster(os.path.join(v_dir, # 'vpvs_depth_slices', # '{0:02}_vpvs.tif'.format(ii, z[ii])), # (v['lon'].min(), v['lat'].min()), # dx*1000, # dy*1000, # vpvs_arr[:, :, ii]) # get shifts mt_east, mt_north, mt_zone = gis_tools.project_point_ll2utm(mt_center[0], mt_center[1]) v_east, v_north, v_zone = gis_tools.project_point_ll2utm(center_point[0], center_point[1]) shift_east = (mt_east-v_east)/1000. shift_north = (mt_north-v_north)/1000. # ============================================================================= # # make vtk arrays # ============================================================================= vtk_x = np.linspace(x.min()-dx, x.max()+dx, len(x)+1)-shift_east vtk_y = np.linspace(y.min()-dy, y.max()+dy, len(y)+1)-shift_north vtk_z = np.append(z, z[-1]) gridToVTK(os.path.join(v_dir, 'roland_vp'), vtk_y, vtk_x, vtk_z,
import numpy as np import matplotlib.pyplot as plt mfn = r"c:\Users\jpeacock\Documents\Geothermal\GraniteSprings\modem_inv\inv_02_tip\gs_prm_err03_tip02_cov03_NLCG_129.rho" dfn = r"c:\Users\jpeacock\Documents\Geothermal\GraniteSprings\modem_inv\inv_02_tip\gs_prm_err03_tip02_cov03_NLCG_129.dat" save_root = 'gsv' rot_angle = 0.0 #--> read model file mod_obj = modem.Model() mod_obj.read_model_file(mfn) #--> get center position model_center = (40.2257922, -118.924755) #model_center = (38.772697, -118.149196) c_east, c_north, c_zone = gis_tools.project_point_ll2utm( model_center[0], model_center[1], 'WGS84') #--> set padding east_pad = 6 north_pad = 6 z_pad = np.where(mod_obj.grid_z > 30000)[0][0] cos_ang = np.cos(np.deg2rad(rot_angle)) sin_ang = np.sin(np.deg2rad(rot_angle)) rot_matrix = np.matrix(np.array([[cos_ang, sin_ang], [-sin_ang, cos_ang]])) #--> write model xyz file lines = [ '# model_type = electrical resistivity', '# model_location = Granite Springs, NV', '# model_author = J Peacock', '# model_organization = U.S. Geological Survey',
east = [] north = [] z = [] vp = [] entries = [] with open(fn, "r") as fid: lines = fid.readlines() for line in lines: if "depth" in line: z.append(float(line.strip().split()[2])) depth = z[-1] else: lat, lon, value = [float(vv) for vv in line.strip().split()] ve, vn, vg = gis_tools.project_point_ll2utm(lat, lon, utm_zone=model_utm_zone) entries.append((lat, lon, vn, ve, depth, value)) # make the entries into an np array for easier use. entries = np.array( entries, dtype=[ ("lat", np.float), ("lon", np.float), ("north", np.float), ("east", np.float), ("depth", np.float), ("vp", np.float), ], )
# -*- coding: utf-8 -*- """ Created on Wed Jul 3 11:10:43 2019 @author: jpeacock """ import pandas as pd from mtpy.utils import gis_tools from pyevtk.hl import pointsToVTK import numpy as np fn = r"c:\Users\jpeacock\OneDrive - DOI\Geysers\Top_Felsite_Points_WGS84.csv" model_center = (38.831979, -122.828190) model_east, model_north, zone = gis_tools.project_point_ll2utm( model_center[0], model_center[1] ) df = pd.read_csv( fn, delimiter=",", usecols=[0, 1, 2], names=["lat", "lon", "depth"], skiprows=1 ) east, north, zone = gis_tools.project_points_ll2utm(df.lat, df.lon) x = (east - model_east) / 1000.0 y = (north - model_north) / 1000.0 z = (df.depth.to_numpy() / 3.25) / 1000.0 pointsToVTK(fn[:-4], y, x, z, {"depth": z})
""" Created on Thu Aug 1 13:33:57 2019 @author: jpeacock """ import pandas as pd import numpy as np from pyevtk.hl import pointsToVTK from mtpy.utils import gis_tools fn = r"c:\Users\jpeacock\OneDrive - DOI\Geysers\Top_Felsite_Points_WGS84.csv" model_center = (38.831979, -122.828190) model_east, model_north, zone = gis_tools.project_point_ll2utm(38.831979, -122.828190, epsg=32610) df = pd.read_csv( fn, names=["lat", "lon", "elev"], usecols=[0, 1, 2], skiprows=1, dtype={ "lat": np.float, "lon": np.float, "elev": np.float }, ) east, north, zone = gis_tools.project_points_ll2utm(df.lat.to_numpy(),
fn = r"c:\Users\jpeacock\Documents\iMush\DLP_Wes.txt" lp_arr = np.loadtxt(fn, delimiter=',', skiprows=1, usecols=[0, 1, 2, 3], dtype={ 'names': ('lat', 'lon', 'depth', 'mag'), 'formats': (np.float, np.float, np.float, np.float) }) 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'],
r"c:\Users\jpeacock\Documents\iMush\vp_depth_slices_ulberg\ulbergVPmodel_Run_124.nc" ) nc_obj = netCDF4.Dataset(nc_fn, "r") depth = nc_obj.variables["depth"][:] lat = nc_obj.variables["latitude"][:] lon = nc_obj.variables["longitude"][:] vp = np.nan_to_num(nc_obj.variables["vp"][:]) dvp = nc_obj.variables["dvp_ulberg_mask"][:] # the arrays are (depth, lat, lon) --> (z, y, x) # taking the transpose will give (lon, lat, depth) --> (x, y, z) lower_left = gis_tools.project_point_ll2utm(lat.min(), lon.min()) upper_right = gis_tools.project_point_ll2utm(lat.max(), lon.max()) d_east = (upper_right[0] - lower_left[0]) / lon.size d_north = (upper_right[1] - lower_left[1]) / lat.size east = np.arange(lower_left[0], upper_right[0] + d_east, d_east) / 1000.0 north = np.arange(lower_left[1], upper_right[1], d_north) / 1000.0 # # for zz in range(depth.size): # raster_fn = os.path.join(r"c:\Users\jpeacock\Documents\iMush\dvp_depth_slices_ulberg", # "{0:02}_dvp_{1:.0f}_WGS84.tif".format(zz, depth[zz])) # raster_fn = raster_fn.replace('-', 'm') # a2r.array2raster(raster_fn, # (float(lon.min()), float(lat.min())), # 1730.0,