Source code for hygra.gravity_grid

#  import sys
#  sys.path.append("/home/mreich/Documents/written/ResearchRepos/hygra/")
import pandas as pd
import numpy as np

from hygra import calculations as calc
from hygra import input_output as io

from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt
#  %matplotlib qt

#############
## classes ##
#############

[docs]class gravityGrid(object): """ Class of a gravityGrid Parameters ---------- dempath : str filepath of the DEM to use. If no DEM is availlable, use value "flat" (default). sensor_coords : list [sensor_x, sensor_y, sensor_z]. Coordinates of the gravity sensor. grid_discr : list [res_x, res_y, res_z] Resolution of the final gravity component grid. grid_domain_x : list [x_min, x_max]. Specifies the x-extent of the grid. grid_domain_y : list [y_min, y_max]. Specifies the y-extent of the grid. grid_domain_vertical : list [z_min, z_max]. Specifies the z-extent of the grid. grid_origin : list [x, y]. Specifies the x and y coordinates of the grid. If not supplied, default to sensor coordinates. grid_shape : str Shape of the gravity grid. Default is "rect" for rectangular. Other option is "circle" for a circular grid. verbose : str Should information be displayed (default = False). Returns ------- Notes ------- """ def __init__(self, dempath, sensor_coords, grid_discr, grid_domain_x, grid_domain_y, grid_domain_vertical, inner_radius = 0, outer_radius = "auto", grid_origin = False, grid_shape = "rect", verbose = False): if verbose: # print('reading dataset {}'.format(os.path.basename(path))) print('reading dataset and constructing gravity component grid..') # construct coherent coordinates and dimensions # not necessary if system is in itself coherent ! # ## information variables self.dempath = dempath self.grid_discretization = grid_discr self.sensor_coordinates = sensor_coords self.grid_domain_x = grid_domain_x self.grid_domain_y = grid_domain_y self.grid_domain_vertical = grid_domain_vertical if grid_origin == False: self.grid_origin = sensor_coords[0:2] else: self.grid_origin = grid_origin self.grid_shape = grid_shape self.grid_method = "None" self.pillar_corrected = False self.pillar_shape = "None" self.grid_radius = min(abs(self.grid_domain_x[0] - self.grid_origin[0]), abs(self.grid_domain_x[1] - self.grid_origin[0]), abs(self.grid_domain_y[0] - self.grid_origin[1]), abs(self.grid_domain_y[1] - self.grid_origin[1]) ) self.inner_radius = inner_radius if self.grid_shape == "circle": self.outer_radius = self.grid_radius elif outer_radius == "auto": self.outer_radius = (abs(min(self.grid_domain_x)) + abs(max(self.grid_domain_x))) / 2 else: self.outer_radius = outer_radius self.topofactor = 0.0 # read DEM # if dempath == 'flat': # self.dem = "no DEM file supplied" # else: # self.dem = rdata.dem(dempath, verbose) # def create_demGrid(self): # # construct grid from DEM # self.demgrid = calc.demGrid(dempath = self.dempath, # discr = self.grid_discretization, # range_x = self.grid_domain_x, # range_y = self.grid_domain_y, # range_z = self.grid_domain_vertical, # shape = self.grid_shape) # # return message # message = "3d grid from DEM was created." # # # return message
[docs] def create_gcompGrid(self, method = "standard"): """ Create DEM grid and gravity component grid of supplied dimensions and properties """ # construct grid from DEM self.demgrid = calc.demGrid(dempath = self.dempath, discr = self.grid_discretization, range_x = self.grid_domain_x, range_y = self.grid_domain_y, range_z = self.grid_domain_vertical, shape = self.grid_shape, inner_cut_radi = self.inner_radius, outer_cut_radi = self.outer_radius, # cut_center = self.sensor_coordinates[0:2] cut_center = self.grid_origin ) # return message message = "3d grid from DEM was created." # construct gravity component grid self.gcompgrid = calc.gcompGrid( demgrid = self.demgrid, sensor = self.sensor_coordinates, discr = self.grid_discretization, gravityMethod = method) # # store grid creation method in class-object self.grid_method = method # return message message = "Gravity component grid was created." # return message
[docs] def summary(self): ## create summary of gravity component grid summary_data = [] summary_data.append(('Dempath: ', self.dempath)) summary_data.append(('Shape of grid: ', self.grid_shape)) summary_data.append(('Grid calculation method: ', self.grid_method)) summary_data.append(('Gravity Sensor coordinates: ', self.sensor_coordinates)) summary_data.append(('Grid discretization [x,y,z]: ', self.grid_discretization)) summary_data.append(('Grid domain X [min, max]: ', self.grid_domain_x)) summary_data.append(('Grid domain Y [min, max]: ', self.grid_domain_y)) summary_data.append(('Grid domain Z [min, max]: ', self.grid_domain_vertical)) summary_data.append(('Grid origin [x, y]: ', self.grid_origin)) summary_data.append(('Grid radius (min, calculated): ', self.grid_radius)) summary_data.append(('Grid inner radius: ', self.inner_radius)) summary_data.append(('Grid outer radius: ', self.outer_radius)) summary_data.append(('Pillar correction applied: ', self.pillar_corrected)) summary_data.append(('Pillar shape: ', self.pillar_shape)) # summary_data.append(('', self.)) # return summary_data
def __str__(self): # str_message = """ Object: gravityGrid ------------------- Dempath: {} Shape of grid: {} Grid calculation method: {} Gravity Sensor coordinates: {} Grid discretization [x,y,z]: {} Grid domain X [min, max]: {} Grid domain Y [min, max]: {} Grid domain Z [min, max]: {} Grid origin [x, y]: {} Grid radius (min, calculated): {} Grid inner radius: {} Grid outer radius: {} Pillar correction applied: {} Pillar shape: {} Topofactor [nm*s-2 / mm]: {} ------------------- """ # return str_message.format( self.dempath, self.grid_shape, self.grid_method, self.sensor_coordinates, self.grid_discretization, self.grid_domain_x, self.grid_domain_y, self.grid_domain_vertical, self.grid_origin, self.grid_radius, self.inner_radius, self.outer_radius, self.pillar_corrected, self.pillar_shape, self.topofactor ) def __repr__(self): # return "{}({!r})".format(self.__class__.__name__, self.__dict__) return self.__str__()
[docs] def topoFactor(self): """ Calculate the topographic conversion factor of the gravity component grid """ # calculate grid based topo factor # rounded to 3 decimals self.topofactor = round(calc.topoFactor(self.gcompgrid, self.grid_discretization, self.grid_radius), 3) # set topofactor as info of class-object return self.topofactor
def topoFactors(self): """ Calculate the topographic conversion factor for each layer of the gravity component grid """ # calculate grid based topo factor # rounded to 3 decimals topofactors = calc.topoFactor(self.gcompgrid, self.grid_discretization, self.grid_radius, single = False) # set topofactor as info of class-object return topofactors
[docs] def correct_pillar_cylinder(self, pillar_radius, pillar_center, extent_z): """ Exclude cylinder shaped body from gravity component grid """ # ## calculate distance of grid cells to pillar center ## old # self.gcompgrid['distance'] = self.gcompgrid.apply(lambda col: calc.distance_between_points(col.x, col.y, 0, pillar_center[0], pillar_center[1], 0), axis=1) self.gcompgrid['distance'] = ((self.gcompgrid.x - pillar_center[0])**2 + (self.gcompgrid.y - pillar_center[1])**2)**.5 ## set value of gcomptgrid zero # for all points within its extent # this is NOT the correct way to do it "copy-warning" # self.gcompgrid.value[(self.gcompgrid.distance <= pillar_radius) & (self.gcompgrid.z >= min(extent_z)) & (self.gcompgrid.z <= max(extent_z))] = 0 # USE: self.gcompgrid.loc[(self.gcompgrid.distance <= pillar_radius) & (self.gcompgrid.z >= min(extent_z)) & (self.gcompgrid.z <= max(extent_z)), 'value'] = 0 # remove 'distance' column self.gcompgrid.drop(['distance'], axis = 1, inplace = True) # set information variables of class self.pillar_corrected = True self.pillar_shape = "cylinder" message = "Corrrected gravity component grid with cylindric pillar" # return message
[docs] def correct_pillar_cuboid(self, extent_x, extent_y, extent_z): """ Exclude cuboid shaped body from gravity component grid """ # ## set value of gcompgrid to zero # for all cells within the xyz-extent # this is NOT the correct way to do it "copy-warning" # self.gcompgrid.value[(self.gcompgrid.x >= min(extent_x)) & (self.gcompgrid.x <= max(extent_x)) & (self.gcompgrid.y >= min(extent_y)) & (self.gcompgrid.y <= max(extent_y)) & (self.gcompgrid.z >= min(extent_z)) & (self.gcompgrid.z <= max(extent_z))] = 0 # USE: self.gcompgrid.loc[(self.gcompgrid.x >= min(extent_x)) & (self.gcompgrid.x <= max(extent_x)) & (self.gcompgrid.y >= min(extent_y)) & (self.gcompgrid.y <= max(extent_y)) & (self.gcompgrid.z >= min(extent_z)) & (self.gcompgrid.z <= max(extent_z)), 'value'] = 0 # # set information variables of class self.pillar_corrected = True self.pillar_shape = "cuboid" ## return message message = "Corrrected gravity component grid with cuboid pillar" # return message
[docs] def return_grid(self): """ Returns the gravity component grid """ return self.gcompgrid
[docs] def plot(self, data = "gcomp", orientation = "horizontal", intersect_horizontal = 1, intersect_vertical = "auto", filepath = "", verbose = False): # if intersect_vertical == "auto": intersect_vertical = self.grid_origin[1] discr_half = self.grid_discretization[1] intersect = intersect_vertical + discr_half ## close old open plot window plt.close() # differenciate plot methods (surface, scatter) # depending on grid.shape if self.grid_shape == "rect": ## select plotting data # horizontal bird-view if orientation == "horizontal": plot_data = self.gcompgrid[self.gcompgrid.nlayer == intersect_horizontal] # reset index plot_data.reset_index(drop=True, inplace=True) # get axis data x_axis = plot_data.x.unique() y_axis = plot_data.y.unique() if data == "gcomp": plot_values = np.array(plot_data.value).reshape((len(y_axis),len(x_axis))) if data == "dem": plot_values = np.array(plot_data.z).reshape((len(y_axis),len(x_axis))) # create plot fig = plt.figure() # ax = fig.subplots(1,2) # dem = ax[0].pcolormesh(x_axis, y_axis, dem_values) # cbar_dem = ax[0].figure.colorbar(dem, ax=ax) # cbar_dem.ax.set_ylabel("DEM", rotation=-90, va="bottom") # gcomps = ax[1].pcolormesh(x_axis, y_axis, g_values) # cbar_gcomps = ax[1].figure.colorbar(gcomps, ax=ax) # cbar_gcomps.ax.set_ylabel("Gravity components", rotation=-90, va="bottom") # ax[0].set_title('DEM grid') # ax[1].set_title('Gravity components') ax = fig.subplots() gridplot2d = ax.pcolormesh(x_axis, y_axis, plot_values, shading="nearest") ax.set_xlabel("x") ax.set_ylabel("y") cbar = ax.figure.colorbar(gridplot2d, ax=ax) if data == "gcomp": cbar.ax.set_ylabel("[nm/s²] / 100% WSC", rotation=-90, va="bottom") ax.set_title('Gravity components') if data == "dem": cbar.ax.set_ylabel("[m]", rotation=-90, va="bottom") ax.set_title('DEM') if verbose: print(x_axis) print(y_axis) print(plot_values) print(plot_data) # vertical profile cut if orientation == "vertical": plot_data = self.gcompgrid[self.gcompgrid.y == intersect] # reset index plot_data.reset_index(drop=True, inplace=True) # get axis data x_axis = plot_data.x.unique() z_axis = plot_data.z.unique() if data == "gcomp": plot_values = np.array(plot_data.value).reshape((-1,len(z_axis))) if data == "dem": plot_values = np.array(plot_data.z).reshape((-1,len(z_axis))) # create plot fig = plt.figure() ax = fig.subplots() # im = ax.pcolormesh(x_axis, z_axis, g_values) im = ax.pcolormesh(x_axis, z_axis, plot_values.T, shading="nearest") ax.set_xlabel("x") ax.set_ylabel("z") # fig = plt.figure() # ax = fig.subplots() # im = ax.imshow(g_values.T) # axis ticks and labels # ax.set_xticks(np.arange(len(x_axis))) # ax.set_yticks(np.arange(len(z_axis))) # ax.set_xticklabels(x_axis) # ax.set_yticklabels(z_axis) cbar = ax.figure.colorbar(im, ax=ax) if data == "gcomp": cbar.ax.set_ylabel("[nm/s²] / 100% WSC", rotation=-90, va="bottom") ax.set_title('Gravity components vertical') if data == "dem": cbar.ax.set_ylabel("[m]", rotation=-90, va="bottom") ax.set_title('DEM') if verbose: print(x_axis) print(z_axis) print(plot_values) print(plot_data) # # if self.grid_shape == "circle": # horizontal bird-view if orientation == "horizontal": plot_data = self.gcompgrid[self.gcompgrid.nlayer == intersect_horizontal] # reset index plot_data.reset_index(drop=True, inplace=True) if data == "gcomp": plt.scatter(plot_data.x, plot_data.y, c=plot_data.value, cmap='viridis') cbar = plt.colorbar(); cbar.set_label("[nm/s²] / 100% WSC", rotation=-90, va="bottom") plt.title('Gravity components') ax = plt.gca() ax.set_facecolor('lightgrey') if data == "dem": plt.scatter(plot_data.x, plot_data.y, c=plot_data.z, cmap='viridis') cbar = plt.colorbar(); cbar.set_label("[m]", rotation=-90, va="bottom") plt.title('DEM') ax = plt.gca() ax.set_facecolor('lightgrey') # vertical profile cut if orientation == "vertical": plot_data = self.gcompgrid[self.gcompgrid.y == intersect] # reset index plot_data.reset_index(drop=True, inplace=True) if data == "gcomp": plt.scatter(plot_data.x, plot_data.z, c=plot_data.value, cmap='viridis') cbar = plt.colorbar(); cbar.set_label("[nm/s²] / 100% WSC", rotation=-90, va="bottom") plt.title('Gravity components vertical') ax = plt.gca() ax.set_facecolor('lightgrey') if data == "dem": plt.scatter(plot_data.x, plot_data.z, c=plot_data.z, cmap='viridis') cbar = plt.colorbar(); cbar.set_label("[m]", rotation=-90, va="bottom") plt.title('DEM') ax = plt.gca() ax.set_facecolor('lightgrey') # # plt.show() # saving figure, if filepath supplied (not empty) if (filepath != ""): plt.savefig(filepath) # message = "Plot created." # how to return plot? return message
[docs] def calc_response(self, mass_change_ts): """ Calculate the gravimetric resonse of a mass change (soil moisture) time series Parameters ---------- mass_change_ts : Pandas.DataFrame() 1D: [timestamps, z, value] or 3D: [timestamps, x, y, z, value]. Timestamps can be either dates or just integers. Value has to be the change in [%] (e.g. for soil moisture 0.23). """ # # gravity_response_ts, _ = calc.gravity_response( gravity_response_ts = calc.gravity_response( gcompgrid = self.gcompgrid, wscgrid = mass_change_ts) # return gravity_response_ts
[docs] def distance_of_signal(self, wsc_vertical, distances = [10,100,250,500,750,1000,1500,2500,5000,10000]): # # order provided distances with biggest first distances.sort(reverse = True) # run loop # calculating gravity response for bound signal_distances = 0 # return signal_distances
[docs] def effect_cylinder_plate(self, change, radius, extent_z): """ Calculate effect of a cylinder plate with limited radius. Parameters ---------- change : int Change of water storage in [mm]. radius : int Limit of cylinder plate (around sensor) in [m]. extent_z : list z-values defining (vertical) start and end of cylinder plate in [m]. Notes ------- Change in [mm] will be converted to [%] considering the absolute z-extent. """ # # calculate percentage of change change_percent = (change/1000) / abs(extent_z[1] - extent_z[0]) # limit gcompgrid to z-extent gcompgrid_cylinder = self.gcompgrid[(self.gcompgrid.z >= min(extent_z)) & (self.gcompgrid.z <= max(extent_z))] # calculate distance to sensor ## old # gcompgrid_cylinder['distance'] = gcompgrid_cylinder.apply(lambda col: calc.distance_between_points(col.x, col.y, 0, self.sensor_coordinates[0], self.sensor_coordinates[1], 0), axis=1) gcompgrid_cylinder['distance'] = ((gcompgrid_cylinder.x - self.sensor_coordinates[0])**2 + (gcompgrid_cylinder.y - self.sensor_coordinates[1])**2)**.5 # limit grid to radius gcompgrid_cylinder = gcompgrid_cylinder[gcompgrid_cylinder.distance <= radius] # sum all gravity components gcomponents = sum(gcompgrid_cylinder.value) # multiply with supplied change value g_response = gcomponents * change_percent # return g_response
def save(self, filepath, compression = False): """ save the grid object as a pickle binary""" # io.save_pickle(self, filepath, compression) # message = 'Gravity grid was saved at ' + filepath ## return return message
[docs]class gravityGridNested(object): """ Class of a nested gravityGrid THIS HAS TO BE CHANGED !!! NOT has nested grid be a class of gravityGrid (wrong hierarchie) BUT nestedGrid has to be constructed as multiple instances of gravityGridNested this way also calculations and the topofactor should work out! Parameters ---------- dempaths : list [dempath_1, ... , dempath_n]. sensor_coords : list [x, y, z]. grid_discrs : list of list [[res_x1, res_y1, res_z1], ... , [res_xn, res_yn, res_zn]]. grid_radii : list [radius_1, ... , radius_n, radius_n+1]. grid_domain_vertical : list [max, min]. grid_origin : list [x, y]. If not supplied, coordinates set to sensor location, verbose : str Should information be displayed (default = False). Returns ------- Notes ------- """ ## debugging # dempaths = ["flat", "flat"] # sensor_coords = [0,0,1] # grid_discr = [[0.5,0.5,.1], [10,10,.5]] # grid_radii = [0,5,100] # grid_domain_vertical = [0, -1] ## def __init__(self, dempaths, sensor_coords, grid_discrs, grid_radii, grid_domain_vertical, grid_origin = False, verbose = False): ## information variables self.dempath = dempaths self.grid_discretization = grid_discrs self.sensor_coordinates = sensor_coords self.grid_radii = grid_radii if grid_origin == False: self.grid_origin = sensor_coords[0:2] else: self.grid_origin = grid_origin self.grid_domain_x = [self.grid_origin[0] - max(grid_radii), self.grid_origin[0] + max(grid_radii)] self.grid_domain_y = [self.grid_origin[1] - max(grid_radii), self.grid_origin[1] + max(grid_radii)] self.grid_domain_vertical = grid_domain_vertical self.grid_shape = "circle" self.grid_method = "None" self.pillar_corrected = False self.pillar_shape = "None" self.grid_radius = min(abs(self.grid_domain_x[0] - self.grid_origin[0]), abs(self.grid_domain_x[1] - self.grid_origin[0]), abs(self.grid_domain_y[0] - self.grid_origin[1]), abs(self.grid_domain_y[1] - self.grid_origin[1]) ) self.topofactor = 0.0 if self.grid_radius/38.2 > abs(self.grid_domain_vertical[1]): message = f""" Warning: the vertical extent is smaller than necessary for a correct calculation of the topoFactor! \\ \n Consider extending the vertical domain until at least {str(round(self.grid_radius/38.2, 1))} m. """ print(message) # read DEM # if dempath == 'flat': # self.dem = "no DEM file supplied" # else: # self.dem = rdata.dem(dempath, verbose) def __str__(self): # str_message = """ Object: gravityGridNested ------------------- Dempath: {} Shape of grid: {} Grid calculation method: {} Gravity Sensor coordinates: {} Grid discretization [x,y,z]: {} Grid nesting radii [min, ... , max]: {} Grid domain X [min, max]: {} Grid domain Y [min, max]: {} Grid domain Z [min, max]: {} Grid origin [x, y]: {} Grid radius (min, calculated): {} Pillar correction applied: {} Pillar shape: {} Topofactor [nm*s-2 / mm]: {} ------------------- """ # return str_message.format( self.dempath, self.grid_shape, self.grid_method, self.sensor_coordinates, self.grid_discretization, self.grid_radii, self.grid_domain_x, self.grid_domain_y, self.grid_domain_vertical, self.grid_origin, self.grid_radius, self.pillar_corrected, self.pillar_shape, self.topofactor ) def __repr__(self): # return "{}({!r})".format(self.__class__.__name__, self.__dict__) return self.__str__()
[docs] def create_gcompGrid(self, method = "standard"): """ Create DEM grid and gravity component grid of supplied dimensions and properties This will create a list of gravityGrid-objects, depending on how many nested grids are desired. """ # # prepare final result grid gcompgrids = [] # loop through all wanted grids # this is based on provided input variables for grid_n in range(len(self.grid_discretization)): inner_radius = self.grid_radii[grid_n] outer_radius = self.grid_radii[grid_n + 1] range_x_temp = [self.sensor_coordinates[0] - outer_radius, self.sensor_coordinates[0] + outer_radius] range_y_temp = [self.sensor_coordinates[1] - outer_radius, self.sensor_coordinates[1] + outer_radius] grid_temp = gravityGrid( dempath = self.dempath[grid_n], sensor_coords = self.sensor_coordinates, grid_discr = self.grid_discretization[grid_n], grid_domain_x = range_x_temp, grid_domain_y = range_y_temp, grid_domain_vertical = self.grid_domain_vertical, inner_radius = inner_radius, outer_radius = outer_radius, grid_origin = False, grid_shape = "circle") grid_temp.create_gcompGrid(method=method) gcompgrids.append(grid_temp) print("created DEM grid from " + str(inner_radius) + " to " + str(outer_radius) + " m") # # store created grids in self.gcompgrids self.gcompgrids = gcompgrids # store grid creation method in class-object self.grid_method = method # return message message = "Nested DEM and gravity component grid was created." # return message
def return_grids(self): """ Returns the gravity component grid """ return self.gcompgrids def correct_pillar_cylinder(self, pillar_radius, pillar_center, extent_z): """ Exclude cylinder shaped body from gravity component grid """ # ## calculate distance of grid cells to pillar center for grid_i in range(len(self.gcompgrids)): self.gcompgrids[grid_i].gcompgrid['distance'] = ((self.gcompgrids[grid_i].gcompgrid.x - pillar_center[0])**2 + (self.gcompgrids[grid_i].gcompgrid.y - pillar_center[1])**2)**.5 ## set value of gcomptgrid zero # for all points within its extent # this is NOT the correct way to do it "copy-warning" # self.gcompgrid.value[(self.gcompgrid.distance <= pillar_radius) & (self.gcompgrid.z >= min(extent_z)) & (self.gcompgrid.z <= max(extent_z))] = 0 # USE: self.gcompgrids[grid_i].gcompgrid.loc[(self.gcompgrids[grid_i].gcompgrid.distance <= pillar_radius) & (self.gcompgrids[grid_i].gcompgrid.z >= min(extent_z)) & (self.gcompgrids[grid_i].gcompgrid.z <= max(extent_z)), 'value'] = 0 # remove 'distance' column self.gcompgrids[grid_i].gcompgrid.drop(['distance'], axis = 1, inplace = True) # set information variables of class self.pillar_corrected = True self.pillar_shape = "cylinder" message = "Corrrected gravity component grid with cylindric pillar" # return message def correct_pillar_cuboid(self, extent_x, extent_y, extent_z): """ Exclude cuboid shaped body from gravity component grid """ # ## set value of gcompgrid to zero for grid_i in range(len(self.gcompgrids)): # for all cells within the xyz-extent # this is NOT the correct way to do it "copy-warning" # self.gcompgrid.value[(self.gcompgrid.x >= min(extent_x)) & (self.gcompgrid.x <= max(extent_x)) & (self.gcompgrid.y >= min(extent_y)) & (self.gcompgrid.y <= max(extent_y)) & (self.gcompgrid.z >= min(extent_z)) & (self.gcompgrid.z <= max(extent_z))] = 0 # USE: self.gcompgrids[grid_i].gcompgrid.loc[(self.gcompgrids[grid_i].gcompgrid.x >= min(extent_x)) & (self.gcompgrids[grid_i].gcompgrid.x <= max(extent_x)) & (self.gcompgrids[grid_i].gcompgrid.y >= min(extent_y)) & (self.gcompgrids[grid_i].gcompgrid.y <= max(extent_y)) & (self.gcompgrids[grid_i].gcompgrid.z >= min(extent_z)) & (self.gcompgrids[grid_i].gcompgrid.z <= max(extent_z)), 'value'] = 0 # # set information variables of class self.pillar_corrected = True self.pillar_shape = "cuboid" ## return message message = "Corrrected gravity component grid with cuboid pillar" # return message def topoFactor(self): """ Calculate the topographic conversion factor of the gravity component grid """ # calculate grid based topo factor topofactor = float() # rounded to 3 decimals for grid in self.gcompgrids: topofactor_grid = round(calc.topoFactor(grid.gcompgrid, grid.grid_discretization, self.grid_radius), 3) print(topofactor_grid) ## add all topofactors topofactor += topofactor_grid # set topofactor as info of class-object self.topofactor = topofactor # return self.topofactor def topoFactors(self): """ Calculate the topographic conversion factor for each layer of the gravity component grid """ # calculate grid based topo factor topofactors = pd.DataFrame() # rounded to 3 decimals for grid in self.gcompgrids: topofactors_tmp = calc.topoFactor(grid.gcompgrid, grid.grid_discretization, self.grid_radius, single = False) topofactors = pd.concat([topofactors, topofactors_tmp]) # set topofactor as info of class-object return topofactors def calc_response(self, mass_change_ts): """ Calculate the gravimetric resonse of a mass change (soil moisture) time series Parameters ---------- mass_change_ts : Pandas.DataFrame() 1D: [timestamps, z, value] or 3D: [timestamps, x, y, z, value]. Timestamps can be either dates or just integers. Value has to be the change in [%] (e.g. for soil moisture 0.23). """ # # gravity_response_ts, _ = calc.gravity_response( gravity_response_ts = float() for grid in self.gcompgrids: gravity_response_ts += calc.gravity_response( gcompgrid = grid.gcompgrid, wscgrid = mass_change_ts ) # return gravity_response_ts def distance_of_signal(self, wsc_vertical, distances = [10,100,250,500,750,1000,1500,2500,5000,10000]): # # order provided distances with biggest first distances.sort(reverse = True) # run loop # calculating gravity response for bound signal_distances = 0 # return signal_distances def effect_cylinder_plate(self, change, radius, extent_z): """ Calculate effect of a cylinder plate with limited radius. Parameters ---------- change : int Change of water storage in [mm]. radius : int Limit of cylinder plate (around sensor) in [m]. extent_z : list z-values defining (vertical) start and end of cylinder plate in [m]. Notes ------- Change in [mm] will be converted to [%] considering the absolute z-extent. """ # # calculate percentage of change change_percent = (change/1000) / abs(extent_z[1] - extent_z[0]) # limit gcompgrid to z-extent gcompgrid_cylinder = pd.DataFrame() for grid in self.gcompgrids: gcompgrid_cylinder_tmp = grid.gcompgrid[(grid.gcompgrid.z >= min(extent_z)) & (grid.gcompgrid.z <= max(extent_z))] gcompgrid_cylinder = pd.concat([gcompgrid_cylinder, gcompgrid_cylinder_tmp]) # calculate distance to sensor ## old # gcompgrid_cylinder['distance'] = gcompgrid_cylinder.apply(lambda col: calc.distance_between_points(col.x, col.y, 0, self.sensor_coordinates[0], self.sensor_coordinates[1], 0), axis=1) gcompgrid_cylinder['distance'] = ((gcompgrid_cylinder.x - self.sensor_coordinates[0])**2 + (gcompgrid_cylinder.y - self.sensor_coordinates[1])**2)**.5 # limit grid to radius gcompgrid_cylinder = gcompgrid_cylinder[gcompgrid_cylinder.distance <= radius] # sum all gravity components gcomponents = sum(gcompgrid_cylinder.value) # multiply with supplied change value g_response = gcomponents * change_percent # return g_response def save(self, filepath, compression = False): """ save the grid object as a pickle binary""" # io.save_pickle(self, filepath, compression) # message = 'Gravity grid was saved at ' + filepath ## return return message def plot(self, data = "gcomp", orientation = "horizontal", intersect_horizontal = 1, intersect_vertical = "auto", limit_radius = False, filepath = "", verbose = False): # if intersect_vertical == "auto": intersect_origin = self.grid_origin[1] else: intersect = intersect_vertical ## close old open plot window plt.close() # differenciate plot methods (surface, scatter) # depending on grid.shape if self.grid_shape == "rect": ## select plotting data # horizontal bird-view if orientation == "horizontal": plot_data = pd.DataFrame() for grid in self.gcompgrids: plot_data_tmp = grid.gcompgrid[grid.gcompgrid.nlayer == intersect_horizontal] cell_vol = grid.grid_discretization[0] * grid.grid_discretization[1] * grid.grid_discretization[2] plot_data_tmp["value"] = plot_data_tmp["value"] / cell_vol print(cell_vol) plot_data = pd.concat([plot_data, plot_data_tmp]) # plot_data = pd.concat([plot_data, grid.gcompgrid[grid.gcompgrid.nlayer == intersect_horizontal]]) # plot_data = pd.concat([plot_data, grid.gcompgrid[grid.gcompgrid.z == profile_intersect]]) if (limit_radius != False): plot_data["distance"] = ((plot_data.x - self.grid_origin[0])**2 + (plot_data.y - self.grid_origin[1])**2)**.5 plot_data = plot_data[plot_data.distance <= limit_radius] plot_data.drop(["distance"], axis = 1, inplace = True) # reset index plot_data.reset_index(drop=True, inplace=True) # get axis data x_axis = plot_data.x.unique() y_axis = plot_data.y.unique() if data == "gcomp": plot_values = np.array(plot_data.value).reshape((len(y_axis),len(x_axis))) if data == "dem": plot_values = np.array(plot_data.z).reshape((len(y_axis),len(x_axis))) # create plot fig = plt.figure() # ax = fig.subplots(1,2) # dem = ax[0].pcolormesh(x_axis, y_axis, dem_values) # cbar_dem = ax[0].figure.colorbar(dem, ax=ax) # cbar_dem.ax.set_ylabel("DEM", rotation=-90, va="bottom") # gcomps = ax[1].pcolormesh(x_axis, y_axis, g_values) # cbar_gcomps = ax[1].figure.colorbar(gcomps, ax=ax) # cbar_gcomps.ax.set_ylabel("Gravity components", rotation=-90, va="bottom") # ax[0].set_title('DEM grid') # ax[1].set_title('Gravity components') ax = fig.subplots() gridplot2d = ax.pcolormesh(x_axis, y_axis, plot_values, shading="nearest") ax.set_xlabel("x") ax.set_ylabel("y") cbar = ax.figure.colorbar(gridplot2d, ax=ax) if data == "gcomp": cbar.ax.set_ylabel("[nm/s²] / 100% WSC", rotation=-90, va="bottom") ax.set_title('Gravity components') if data == "dem": cbar.ax.set_ylabel("[m]", rotation=-90, va="bottom") ax.set_title('DEM') if verbose: print(x_axis) print(y_axis) print(plot_values) print(plot_data) # vertical profile cut if orientation == "vertical": plot_data = pd.DataFrame() for grid in self.gcompgrids: if intersect_vertical == "auto": intersect = intersect_origin + grid.grid_discretization[1]/2 plot_data_tmp = grid.gcompgrid[grid.gcompgrid.y == intersect] cell_vol = grid.grid_discretization[0] * grid.grid_discretization[1] * grid.grid_discretization[2] plot_data_tmp["value"] = plot_data_tmp["value"] / cell_vol print(cell_vol) plot_data = pd.concat([plot_data, plot_data_tmp]) if (limit_radius != False): plot_data["distance"] = ((plot_data.x - self.grid_origin[0])**2 + (plot_data.y - self.grid_origin[1])**2)**.5 plot_data = plot_data[plot_data.distance <= limit_radius] plot_data.drop(["distance"], axis = 1, inplace = True) # plot_data = pd.concat([plot_data, grid.gcompgrid[grid.gcompgrid.y == intersect]]) # reset index plot_data.reset_index(drop=True, inplace=True) # get axis data x_axis = plot_data.x.unique() z_axis = plot_data.z.unique() if data == "gcomp": plot_values = np.array(plot_data.value).reshape((-1,len(z_axis))) if data == "dem": plot_values = np.array(plot_data.z).reshape((-1,len(z_axis))) # create plot fig = plt.figure() ax = fig.subplots() # im = ax.pcolormesh(x_axis, z_axis, g_values) im = ax.pcolormesh(x_axis, z_axis, plot_values.T, shading="nearest") ax.set_xlabel("x") ax.set_ylabel("z") # fig = plt.figure() # ax = fig.subplots() # im = ax.imshow(g_values.T) # axis ticks and labels # ax.set_xticks(np.arange(len(x_axis))) # ax.set_yticks(np.arange(len(z_axis))) # ax.set_xticklabels(x_axis) # ax.set_yticklabels(z_axis) cbar = ax.figure.colorbar(im, ax=ax) if data == "gcomp": cbar.ax.set_ylabel("[nm/s²] / 100% WSC", rotation=-90, va="bottom") ax.set_title('Gravity components vertical') if data == "dem": cbar.ax.set_ylabel("[m]", rotation=-90, va="bottom") ax.set_title('DEM') if verbose: print(x_axis) print(z_axis) print(plot_values) print(plot_data) # # if self.grid_shape == "circle": # horizontal bird-view if orientation == "horizontal": plot_data = pd.DataFrame() for grid in self.gcompgrids: plot_data_tmp = grid.gcompgrid[grid.gcompgrid.nlayer == intersect_horizontal] cell_vol = grid.grid_discretization[0] * grid.grid_discretization[1] * grid.grid_discretization[2] plot_data_tmp["value"] = plot_data_tmp["value"] / cell_vol print(cell_vol) plot_data = pd.concat([plot_data, plot_data_tmp]) if (limit_radius != False): plot_data["distance"] = ((plot_data.x - self.grid_origin[0])**2 + (plot_data.y - self.grid_origin[1])**2)**.5 plot_data = plot_data[plot_data.distance <= limit_radius] plot_data.drop(["distance"], axis = 1, inplace = True) # plot_data = pd.concat([plot_data, grid.gcompgrid[grid.gcompgrid.nlayer == intersect_horizontal]]) # reset index plot_data.reset_index(drop=True, inplace=True) if data == "gcomp": plt.scatter(plot_data.x, plot_data.y, c=plot_data.value, cmap='viridis') cbar = plt.colorbar(); cbar.set_label("[nm/s²] / 100% WSC", rotation=-90, va="bottom") plt.title('Gravity components') ax = plt.gca() ax.set_facecolor('lightgrey') if data == "dem": plt.scatter(plot_data.x, plot_data.y, c=plot_data.z, cmap='viridis') cbar = plt.colorbar(); cbar.set_label("[m]", rotation=-90, va="bottom") plt.title('DEM') ax = plt.gca() ax.set_facecolor('lightgrey') # vertical profile cut if orientation == "vertical": plot_data = pd.DataFrame() for grid in self.gcompgrids: if intersect_vertical == "auto": intersect = intersect_origin + grid.grid_discretization[1]/2 plot_data_tmp = grid.gcompgrid[grid.gcompgrid.y == intersect] cell_vol = grid.grid_discretization[0] * grid.grid_discretization[1] * grid.grid_discretization[2] plot_data_tmp["value"] = plot_data_tmp["value"] / cell_vol print(cell_vol) plot_data = pd.concat([plot_data, plot_data_tmp]) # plot_data = pd.concat([plot_data, grid.gcompgrid[grid.gcompgrid.y == intersect]]) if (limit_radius != False): plot_data["distance"] = ((plot_data.x - self.grid_origin[0])**2 + (plot_data.y - self.grid_origin[1])**2)**.5 plot_data = plot_data[plot_data.distance <= limit_radius] plot_data.drop(["distance"], axis = 1, inplace = True) # reset index plot_data.reset_index(drop=True, inplace=True) if data == "gcomp": plt.scatter(plot_data.x, plot_data.z, c=plot_data.value, cmap='viridis') cbar = plt.colorbar(); cbar.set_label("[nm/s²] / 100% WSC", rotation=-90, va="bottom") plt.title('Gravity components vertical') ax = plt.gca() ax.set_facecolor('lightgrey') if data == "dem": plt.scatter(plot_data.x, plot_data.z, c=plot_data.z, cmap='viridis') cbar = plt.colorbar(); cbar.set_label("[m]", rotation=-90, va="bottom") plt.title('DEM') ax = plt.gca() ax.set_facecolor('lightgrey') # # plt.show() # saving figure, if filepath supplied (not empty) if (filepath != ""): plt.savefig(filepath) # message = "Plot created." # how to return plot? return message
############### ## functions ## ###############
[docs]def load_gravityGrid(filepath, compressed = True): """Load a saved gravity component grid class with all processed attributes""" # load binary pickle object data_tmp = io.load_pickle(filepath, compressed) ## return object return data_tmp