Source code for hygra.calculations

import pandas as pd
import numpy as np
import dask.dataframe as dd
import dask.array as da 
import math
import rasterio
import swifter
# from rasterio.transform import from_bounds, from_origin
from scipy.interpolate import griddata
from scipy.interpolate import interp1d
from scipy.interpolate import interpn
from scipy.interpolate import RegularGridInterpolator
import pickle
#  from rasterio.warp import reproject, Resampling
#  import pyvista as pv

## constants
# for gravity component calculations
## gravitational constant
# m³/(kg*s²)
gamma = 6.6743015e-11
## density of water
#  kg/m³
rho = 1000
## conversion of decimals to get desired units
# gravity units nm/s²
w = 1e9
# gravity units µGal
# w = 1e8

[docs]def topoFactor(gcompgrid, discr, grid_radius, single = True, unit = "nms-2/mm"): """ Calculate the topography factor of a gravity component grid Parameters ---------- gcompgrid : Pandas.DataFrame() In format [x, y, z, nlayer, value]. discr : list() List of float values of the grid discretization in x,y,z direction. grid_radius : float() Extent of the grid from the gravimeter towards the edge of the grid in [m]. This is essential for the calculatin of the vertical grid extent for the topofactor, in order to make it comparable to the Bouguer effect. single : boolean Wether to calculate ONE overall topofactor (True) or individual factors for all individual grid layers (False). Default is True. unit : str Output unit. Options are "nms-2/mm" (default) or "mm/nms-2". Returns ------ int Value indicates: if unit = "nms-2/mm": equivalent change in gravity for change in water storage of 1 mm. if unit = "mm/nms-2": equivalent change in mm water storage gravity for gravity change of 1 nm/s². """ ## change in water (mass) ## 1 mm water over 1m² = 0.001 m³ # Vchange = 0.001 # [m] Hchange = 0.001 if single: ## convert from [m] to [mm] # the gcompGrid has coordinates in [m] ## most importantly, the depth for the calculation has to be based on the overall grid extent # this follows the formula (for 97% of the signal): # z = radius / 38.2 (based on tangens of the cone of influence) # 38.2 = tan(177°/2) depth_for_effect = grid_radius / 38.2 num_layers = math.ceil(depth_for_effect / discr[2]) # limit vertical grid extent to "necessary" grid for Bouguer comparison values # gravity_layers = gcompgrid[gcompgrid.z > (sensor_coords[2]-depth_for_effect)].groupby(["nlayer"])['value'].sum() gravity_layers = gcompgrid.groupby(["nlayer"])['value'].sum() # limit layers vertically, parallel to the topography # following the criteria of the vertical extent, based on cone-of-signal gravity_layers_effect = gravity_layers.reset_index()[gravity_layers.to_frame().reset_index().nlayer <= num_layers] dW = Hchange / discr[2] topofactor = (gravity_layers_effect["value"] * dW).mean() # nlayers = depth_for_effect / discr[2] # dW = (Vchange * discr[0] * discr[1]) / (discr[0] * discr[1] * discr[2]) * 1/nlayers # topofactor = topogrid * dW # # convert unit, if descired if unit == "mm/nms-2": topofactor = 1/topofactor # return topofactor else: gravity_layers = gcompgrid.groupby(['nlayer'])['value'].sum() topofactors = gravity_layers.to_frame() topofactors.reset_index(inplace = True) topofactors["dz"] = discr[2] topofactors["cell_center"] = topofactors.dz.cumsum() - topofactors.dz/2 # nlayers = 1 # dW = (0.001 * discr[0] * discr[1]) / (discr[0] * discr[1] * discr[2]) * 1/nlayers dW = Hchange / discr[2] topofactors["factor"] = topofactors.value * dW # return topofactors
[docs]def demGrid(dempath, discr, range_x, range_y, range_z, shape = "rect", inner_cut_radi = 0, outer_cut_radi = 0, cut_center = [0,0]): """ Create Grid based on flat topography or a supplied DEM Parameters ---------- dempath : str Path to DEM file. So far only ASCII-format is supported. For no DEM to be used (=flat topography) set dempath to "flat". discr : array (3 items) Discretization [x, y, z] of demgrid in [m]. range_x : array (2 items) Coordinates of output grid domain in X direction. [xmin, xmax]. range_y : array (2 items) Coordinates of output grid domain in Y direction. [ymin, ymax]. range_z : int or array (2 items) Coordinates of output grid domain in Z direction. [zmin, zmax]. If a DEM file is supplied and used, set range_z to absolute extent below surface (single integer or float). shape : string Defines the shape of the grid to be created. Options are "rect" for rectangular and "circ" for circular. Default is "rect". inner_cut_radi : float Radius in [m] for the inner cut-out circle. Given value will still be included. outer_cut_radi : float Radius in [m] for the outer cut-out circle. Given value will already be cut out (excluded). cut_center : array (2 items) [x, y] giving the center of the cutout. Returns ------ Pandas.DataFrame() Containing columns (x,y,z,nlayer). describ columns... """ # check if dem was supplied # no dem supplied # considering flat topography ## DEBUGGIUNG # dempath = "/home/mreich/Documents/projects/Wettzell/Data/DEM/WE_UP_TO_300m_05m.asc" # dempath = "/home/mreich/Documents/written/ResearchRepos/hygra/data/testgrid_local.asc" # dempath = "/home/mreich/Documents/written/ResearchRepos/hygra/data/testgrid_local2.asc" # dempath = "/home/mreich/Documents/written/ResearchRepos/hygra/data/testgrid.asc" # dempath = "/home/mreich/Documents/projects/Torgau_UFZ/Data/Input/DEM/DEMstitched_inner2km_2mres.asc" # dempath = "flat" # sensor = [361788.86,5708362.12,97] # range_x = [sensor[0] - 50, sensor[0] + 50] # range_y = [sensor[1] - 50, sensor[1] + 50] # range_y = [-2, 2] # range_z = [0, -10] # range_z = 2 # discr = [.1, .1, .1] # inner_cut_radi = 0 # outer_cut_radi = 50 ## prepare 2d final grid parameters ## get grid extents # xcount = abs(max(range_x)) + abs(min(range_x)) # ycount = abs(max(range_y)) + abs(min(range_y)) #### # dempath = "flat" # range_x = [-10, 10] # range_y = [-10, 10] # range_x = [-50, 50] # range_y = [-50, 50] # # for flat grid # range_z = [0, -5] # range_z = [0, -15] # discr = [.1, .1, .1] # origin = [0, 0] # sensor_height = 0.25 # sensor = [3,0,0 + sensor_height] # inner_cut_radi = 0 # outer_cut_radi = 50 # cut_center = [0,0] ## # dempath = file_dem_station # dempath = file_dem + str(station.Name) + "_try.asc" # discr = [1, 1, 1] # inner_cut_radi = 0 # outer_cut_radi = 50 # cut_center = origin # range_x = [origin[0] - outer_cut_radi, origin[0] + outer_cut_radi] # range_y = [origin[1] - outer_cut_radi, origin[1] + outer_cut_radi] # range_z = range_z #### xcount = max(range_x) - min(range_x) ycount = max(range_y) - min(range_y) ## get number of cells in each direction xnum = int(xcount / discr[0]) ynum = int(ycount / discr[1]) ## span spaces (coordinates) in each direction x_space = np.linspace(min(range_x) + 0.5*discr[0], max(range_x) - 0.5*discr[0], xnum) # y_space = np.linspace(min(range_y) + discr[1], max(range_y) - discr[1], ynum) y_space = np.linspace(max(range_y) - 0.5*discr[1], min(range_y) + 0.5*discr[1], ynum) ## grid if only flat topography is considered if dempath == "flat": # manage z-space zcount = abs(max(range_z) - min(range_z)) znum = int(zcount / discr[2]) z_space = np.linspace(max(range_z) - 0.5*discr[2], min(range_z) + 0.5*discr[2], znum) ## create meshgrid xgrid, ygrid, zgrid = np.meshgrid(x_space, y_space, z_space) # add column with layer counts nlayer = np.repeat(np.expand_dims(np.cumsum(np.repeat(1, znum)), axis = 0), (xgrid.shape[0] * xgrid.shape[1]), axis = 0).flatten() ## constructing grid based on DEM supplied topography else: # read dem data into numpy structure (2d grid + z-data) with rasterio.open(dempath) as demdata: ## span spaces (coordinates) in each direction x_space_org = np.linspace(demdata.bounds.left, demdata.bounds.right, demdata.width) y_space_org = np.linspace(demdata.bounds.top, demdata.bounds.bottom, demdata.height) # get DEM data print("reading DEM..") dem_data = demdata.read() print("finished reading DEM.") # # construct dem grid xgrid_org, ygrid_org = np.meshgrid(x_space_org, y_space_org) xgrid_org_flat = xgrid_org.flatten(order='C') ygrid_org_flat = ygrid_org.flatten(order='C') dem_data_flat = dem_data.flatten(order='C') # construct final (desired) 2d grid (using input variables) xgrid2d, ygrid2d = np.meshgrid(x_space, y_space) # interpolate data_grid onto final grid print("interpolating grid from DEM..") demdata_interpolated = griddata((xgrid_org_flat, ygrid_org_flat), dem_data_flat, (xgrid2d, ygrid2d), method='linear') # demdata_interpolated = griddata((xgrid_org, ygrid_org), dem_data[0][0], (xgrid2d, ygrid2d), method='linear') # -> this way subsettings and changing resolution is already done at once # prepare z parameters for final grid # range_z = 2 zcount = abs(max(range_z) - min(range_z)) znum = int(zcount / discr[2]) # z_vertical = np.repeat(-1 * 0.5*discr[2], znum) z_vertical = np.repeat(-1 * discr[2], znum) z_space = np.cumsum(z_vertical) # create final mesh with still no real (but correction) z-values xgrid, ygrid, zgrid_cor = np.meshgrid(x_space, y_space, z_space) # extent z-direction # here all original z griddata (dem_data) have to be added to [cummulated] zgrid_cor layers ## replicate demdata for number znum of z-layers # demdata3d_interpolated = np.repeat(demdata_interpolated[None,...],znum,axis=0) # bring in correct shape demdata3d_interpolated = np.reshape(np.repeat(demdata_interpolated.flatten(), znum), (-1, xgrid.shape[0], xgrid.shape[0])) demdata3d_interpolated = demdata3d_interpolated.reshape(xgrid.shape) # add both layers zgrid = zgrid_cor + demdata3d_interpolated # # add column with layer counts # nlayer = np.repeat(np.cumsum(np.repeat(1, znum)), (xgrid.shape[0] * xgrid.shape[1])) nlayer = np.repeat(np.expand_dims(np.cumsum(np.repeat(1, znum)), axis = 0), (xgrid.shape[0] * xgrid.shape[1]), axis = 0).flatten() # ## plotting # import matplotlib.pyplot as plt # # org # plt.contourf(xgrid_org,ygrid_org,dem_data[0])#,15,cmap=plt.cm.jet) # plt.colorbar() # plt.show() # # interp # plt.contourf(xgrid2d,ygrid2d,demdata_interpolated)#,15,cmap=plt.cm.jet) # plt.colorbar() # plt.show() # ## convert final grid to pd.dataframe # set up data data = { "x": xgrid.flatten(), "y": ygrid.flatten(), "z": zgrid.flatten(), "nlayer": nlayer } # # get total number of points # numPoints = np.product(xgrid.shape) # data = { # "x": np.reshape(xgrid,numPoints), # "y": np.reshape(ygrid,numPoints), # "z": np.reshape(zgrid,numPoints), # "nlayer": nlayer # } # create dataframe demgrid = pd.DataFrame(data=data) # apply point exclusion in case of circular DEM shape if shape == "circle": # calculate 2d horizontal distances print("cutting demgrid to circle shape") ## old # demgrid['distance'] = demgrid.apply(lambda col: distance_between_points(col.x, col.y, 0, cut_center[0], cut_center[1], 0), axis=1) demgrid['distance'] = ((demgrid.x - cut_center[0])**2 + (demgrid.y - cut_center[1])**2)**.5 # cut out inner circle demgrid = demgrid[demgrid.distance >= inner_cut_radi] # value of inner circe will still be included demgrid = demgrid[demgrid.distance < outer_cut_radi] # cut out outer cirle print(demgrid) # value of outer_radii will be excluded # remove 'distance' column demgrid.drop(['distance'], axis = 1, inplace = True) # return gem grid as pandas data.frame return demgrid
[docs]def gcompGrid(demgrid, sensor, discr, gravityMethod = "standard"): """ Create a grid of gravity components Considered is a mass change per grid cell of 100%. This has to be taken into account when multiplying with mass change values, e.g. WSC Soil moisture values thus have to be used as 0.7 and NOT percent (70%)! Parameters ---------- demgrid : Pandas.DataFrame() 3d grid [x, y, z]. sensor : array (3 items) Coordinates of the gravity sensor [x, y, z]. discr : array (3 items) Discretization [x, y, z] of demgrid in [m]. gravityMethod : str Options are "standard", "pointmass", "macmillan", "forsberg". See Details. Returns ------ Pandas.DataFrame() with column 'value' containing the gravity components. Notes ------ The gravity components are in 100% mass change for each cell. The unit of the gravity component is [nm/s²]. Method: for the standard method, grid points are calculated with different gravity formulas, depending on their distance to the gravity sensor location. For a rough estimate, the following is valid: distance < 50 m: gravity_forsberg() is used. distance > 50 & < 1000 m: gravity_macmillan() is used. distance > 1000 m: gravity_pointmass() is used. Convention: for error-less joining, averaging, binning, etc. are all X, Y, Z values rounded to 2 decimal placesself. This implies the unit of [m] in order to get [cm] precise coordinates. """ ## DEBUGGING # demgrid = testgrid # sensor = [0,0,0] # discr = [.5, .5, .5] ## print("starting gravity component grid creation..") ## standard method if gravityMethod == "standard": # # this means after the radius (distance), # either forsberg, macmillan or pointmass formulas are used for the calculation # radius criteria based on: # r2exac=2^2 #bei 2.5 x 2.5 cellsizes ~= 50 m # r2macm=9^2 #bei 2.5 x 2.5 cellsizes ~= 1000 m r_inner = 50 #[m] r_outer = 1000 #[m] # # create results dataframe gcompgrid = pd.DataFrame() # # calculate distance of each grid cell to sensor locati0n ## old # demgrid['distance'] = demgrid.apply(lambda col: distance_between_points(col.x, col.y, col.z, sensor[0], sensor[1], sensor[2]), axis=1) ## changing column datatype (for faster execution) demgrid.x = demgrid.x.astype(np.float32) demgrid.y = demgrid.y.astype(np.float32) demgrid.z = demgrid.z.astype(np.float32) demgrid['distance'] = ((demgrid.x - sensor[0])**2 + (demgrid.y - sensor[1])**2 + (demgrid.z - sensor[2])**2)**.5 demgrid.distance = demgrid.distance.astype(np.float32) print(demgrid) # split grids into 3 distanc criteria # forsberg : the closest to sensor grid_forsberg = demgrid[demgrid.distance <= r_inner].copy().reset_index(drop=True) # check if dataframe is empty if grid_forsberg.shape[0] > 0: # calculate needed 'helping points' # grid_forsberg.loc[:,'xl'] = grid_forsberg.x - (0.5 * discr[0]) # grid_forsberg.loc[:,'xr'] = grid_forsberg.x + (0.5 * discr[0]) # grid_forsberg.loc[:,'yl'] = grid_forsberg.y - (0.5 * discr[1]) # grid_forsberg.loc[:,'yr'] = grid_forsberg.y + (0.5 * discr[1]) # grid_forsberg['yl'] = -1* (0.5 * discr[1]) + grid_forsberg.loc[:,'y'] # grid_forsberg['yr'] = +1* (0.5 * discr[1]) + grid_forsberg.loc[:,'y'] # grid_forsberg.loc[:,'Zint'] = grid_forsberg.z + (0.5 * discr[2]) # grid_forsberg.loc[:,'Zend'] = grid_forsberg.z - (0.5 * discr[2]) grid_forsberg['xl'] = grid_forsberg.loc[:,'x'] - (0.5 * discr[0]) grid_forsberg['xr'] = grid_forsberg.loc[:,'x'] + (0.5 * discr[0]) # grid_forsberg['yl'] = grid_forsberg.loc[:,'y'].copy() # grid_forsberg['xx'] = grid_forsberg.loc[:,'y'].copy() # grid_forsberg['yl'] = grid_forsberg.loc[:,'yl'] - (0.5 * discr[1]) # grid_forsberg['xx'] = grid_forsberg.loc[:,'xx'] + (0.5 * discr[1]) # grid_forsberg['yl'] = (grid_forsberg.loc[:,'y'] - (0.5 * discr[1])) # grid_forsberg['yr'] = (grid_forsberg.loc[:,'y'] + (0.5 * discr[1])) # grid_forsberg['ylx'] = -1* (0.5 * discr[1]) grid_forsberg['yl'] = grid_forsberg.loc[:,'ylx'] + grid_forsberg.loc[:,'y'] grid_forsberg['yrx'] = +1* (0.5 * discr[1]) grid_forsberg['yr'] = grid_forsberg.loc[:,'yrx'] + grid_forsberg.loc[:,'y'] grid_forsberg['samey'] = (grid_forsberg.yr == grid_forsberg.yl) grid_forsberg['samex'] = (grid_forsberg.xr == grid_forsberg.xl) # grid_forsberg['Zint'] = grid_forsberg.loc[:,'z'] + (0.5 * discr[2]) grid_forsberg['Zend'] = grid_forsberg.loc[:,'z'] - (0.5 * discr[2]) print("parameter setting..") print(grid_forsberg) # calculate gravity components grid_forsberg['value'] = grid_forsberg.swifter.apply(lambda col: gravity_forsberg( xl = col.xl, xr = col.xr, yl = col.yl, yr = col.yr, Zint = col.Zint, Zend = col.Zend, xs = sensor[0], ys = sensor[1], zs = sensor[2] ), axis = 1) print("after calculations..") print(grid_forsberg) # drop 'helping points' from data.frame grid_forsberg.drop(['xl', 'xr', 'yl', 'yr', 'Zint', 'Zend', 'ylx', 'yrx', 'samey', 'samey'], axis = 1, inplace = True) print("after dropping columns..") print(grid_forsberg) # append to result dataframe # gcompgrid = gcompgrid.append(grid_forsberg) gcompgrid = gcompgrid.append(grid_forsberg) # # macmillan : intermediate distance grid_macmillan = demgrid[(demgrid.distance > r_inner) & (demgrid.distance < r_outer)].copy().reset_index(drop=True) # check if dataframe is empty if grid_macmillan.shape[0] > 0: # calculate gravity components grid_macmillan['value'] = grid_macmillan.swifter.apply(lambda col: gravity_macmillan( dx = discr[0], dy = discr[1], dz = discr[2], rad = col.distance, xp = col.x, yp = col.y, zp = col.z, xs = sensor[0], ys = sensor[1], zs = sensor[2] ), axis = 1) # # append to result dataframe gcompgrid = gcompgrid.append(grid_macmillan) # # pointmass : furthest away from sensor grid_pointmass = demgrid[demgrid.distance >= r_outer].copy().reset_index(drop=True) # check if dataframe is empty if grid_pointmass.shape[0] > 0: # calculate gravity components grid_pointmass['value'] = grid_pointmass.swifter.apply(lambda col: gravity_pointmass( dx = discr[0], dy = discr[1], dz = discr[2], rad = col.distance, zs = sensor[2], zp = col.z ), axis = 1) # # append to result dataframe gcompgrid = gcompgrid.append(grid_pointmass) ## combine all grids # gcompgrid = gcompgrid.append(grid_forsberg), grid_macmillan), grid_pointmass) # ## use only pointmass if gravityMethod == "pointmass": # calculate distance of each grid cell to sensor location # demgrid['distance'] = demgrid.apply(lambda col: distance_between_points(col.x, col.y, col.z, sensor[0], sensor[1], sensor[2]), axis=1) ## changing column datatype (for faster execution) demgrid.x = demgrid.x.astype(np.float32) demgrid.y = demgrid.y.astype(np.float32) demgrid.z = demgrid.z.astype(np.float32) demgrid['distance'] = ((demgrid.x - sensor[0])**2 + (demgrid.y - sensor[1])**2 + (demgrid.z - sensor[2])**2)**.5 demgrid.distance = demgrid.distance.astype(np.float32) # calculate gravity components demgrid['value'] = demgrid.swifter.apply(lambda col: gravity_pointmass( dx = discr[0], dy = discr[1], dz = discr[2], rad = col.distance, zs = sensor[2], zp = col.z ), axis = 1) # rename for consistent output variable gcompgrid = demgrid # ## use only macmillan if gravityMethod == "macmillan": # calculate distance of each grid cell to sensor location # demgrid['distance'] = demgrid.apply(lambda col: distance_between_points(col.x, col.y, col.z, sensor[0], sensor[1], sensor[2]), axis=1) ## changing column datatype (for faster execution) demgrid.x = demgrid.x.astype(np.float32) demgrid.y = demgrid.y.astype(np.float32) demgrid.z = demgrid.z.astype(np.float32) demgrid['distance'] = ((demgrid.x - sensor[0])**2 + (demgrid.y - sensor[1])**2 + (demgrid.z - sensor[2])**2)**.5 demgrid.distance = demgrid.distance.astype(np.float32) # calculate gravity components demgrid['value'] = demgrid.swifter.apply(lambda col: gravity_macmillan( dx = discr[0], dy = discr[1], dz = discr[2], rad = col.distance, xp = col.x, yp = col.y, zp = col.z, xs = sensor[0], ys = sensor[1], zs = sensor[2] ), axis = 1) # rename for consistent output variable gcompgrid = demgrid # ## use only forsberg if gravityMethod == "forsberg": # calculate distance of each grid cell to sensor location # demgrid['distance'] = demgrid.apply(lambda col: distance_between_points(col.x, col.y, col.z, sensor[0], sensor[1], sensor[2]), axis=1) ## changing column datatype (for faster execution) demgrid.x = demgrid.x.astype(np.float32) demgrid.y = demgrid.y.astype(np.float32) demgrid.z = demgrid.z.astype(np.float32) demgrid['distance'] = ((demgrid.x - sensor[0])**2 + (demgrid.y - sensor[1])**2 + (demgrid.z - sensor[2])**2)**.5 demgrid.distance = demgrid.distance.astype(np.float32) # calculate needed 'helping points' demgrid.loc[:,'xl'] = demgrid.x - (0.5 * discr[0]) demgrid.loc[:,'xr'] = demgrid.x + (0.5 * discr[0]) # demgrid.loc[:,'yl'] = demgrid.y - (0.5 * discr[1]) # demgrid.loc[:,'yr'] = demgrid.y + (0.5 * discr[1]) demgrid.loc[:,'Zint'] = demgrid.z + (0.5 * discr[2]) demgrid.loc[:,'Zend'] = demgrid.z - (0.5 * discr[2]) demgrid['ylx'] = -1* (0.5 * discr[1]) demgrid['yl'] = demgrid.loc[:,'ylx'] + demgrid.loc[:,'y'] demgrid['yrx'] = +1* (0.5 * discr[1]) demgrid['yr'] = demgrid.loc[:,'yrx'] + demgrid.loc[:,'y'] demgrid['samey'] = (demgrid.yr == demgrid.yl) demgrid['samex'] = (demgrid.xr == demgrid.xl) # calculate gravity components demgrid['value'] = demgrid.swifter.apply(lambda col: gravity_forsberg( xl = col.xl, xr = col.xr, yl = col.yl, yr = col.yr, Zint = col.Zint, Zend = col.Zend, xs = sensor[0], ys = sensor[1], zs = sensor[2] ), axis = 1) # drop 'helping points' from data.frame print(demgrid) demgrid.drop(['xl', 'xr', 'yl', 'yr', 'Zint', 'Zend', 'yrx', 'ylx', 'samex', 'samey'], axis = 1, inplace = True) # rename for consistent output variable gcompgrid = demgrid # # remove 'distance' column gcompgrid.drop(['distance'], axis = 1, inplace = True) # ## round x and y values to [cm] = 2 decimal places gcompgrid.x = round(gcompgrid.x, 2) gcompgrid.y = round(gcompgrid.y, 2) gcompgrid.z = round(gcompgrid.z, 2) # ## return created grid return gcompgrid
[docs]def gravity_macmillan(dx, dy, dz, rad, xp, yp, zp, xs, ys, zs): """ Calculate the gravimetric attraction using the approach from MacMillan. """ # [nm/s²], depending on value of 'w' # see declaration of constants at the top of this file # calculations for distances alfa = 2*dx**2-dy**2-dz**2 beta = -dx**2+2*dy**2-dz**2 ome = -dx**2-dy**2+2*dz**2 abg = alfa*(xp-xs)**2+beta*(yp-ys)**2+ome*(zp-zs)**2 # 3 different macmillan terms tm1 = -((zp-zs)/rad**3) tm2 = -5/24*(zp-zs)*abg/rad**7 tm3 = ome/12*(zp-zs)/rad**5 ##12!?! benjamin hatte hier mal eine 24 stehen...warum?? # multiply together for final result for this layer, # spacial extent R&C and for one step in time gravity_value = w*gamma*rho*dx*dy*dz*(tm1+tm2+tm3) # return gravity_value
[docs]def gravity_pointmass(dx, dy, dz, rad, zs, zp): """ Calculate the gravimetric attraction using the approach of pointmasses. """ # [nm/s²], depending on value of 'w' # see declaration of constants at the top of this file gravity_value = -w*gamma*rho*dx*dy*dz*(zp-zs)/rad**3 return gravity_value
[docs]def gravity_forsberg(xl, xr, yl, yr, Zint, Zend, xs, ys, zs): """ Calculate the gravimetric attraction using the approach from Forsberg. """ # [nm/s²], depending on value of 'w' # see declaration of constants at the top of this file #distance mass to SG x = [xl-xs, xr-xs] y = [yl-ys, yr-ys] z = [Zint-zs, Zend-zs] # for sign switching of summation sign= [1,2] # sum = 0 for xi, x_cnt in zip(x, sign): for yi, y_cnt in zip(y, sign): for zi, z_cnt in zip(z, sign): rf = math.sqrt(xi**2+yi**2+zi**2) sum = sum + (-1)**(x_cnt+y_cnt+z_cnt) * (xi*math.log(yi+rf)+yi*math.log(xi+rf)-zi*math.atan(xi*yi/zi/rf)) # gravity_value = -w*gamma*rho*sum # return gravity_value
[docs]def distance_between_points(x, y, z, xi, yi, zi): """ Calculate the distance between two points in 3d space. """ distance = math.sqrt((x - xi)**2 + (y - yi)**2 + (z - zi)**2) # return value return distance
[docs]def gravity_bouguerplate(water_storage_change): """ Calculate the gravity effect of the Bouguer plate, resulting from water storage changes Parameters ---------- water_storage_change : int Size of water storage change in [mm]. Returns ------ Gravity effect in [nm/s²] Notes ------- Bougher: delta g = 2pi * G * density_water * delta h """ # gravity_effect = 2 * math.pi * gamma * rho * w * water_storage_change / 1000 # return gravity_effect
[docs]def gravity_response(gcompgrid, wscgrid, boundary_values = 'extrapolate'): """ Calculate gravity change from water storage changes (wsc) grid Parameters ---------- gcompgrid : Pandas.Data.Frame() Gravity component grid in format [x, y, z, value]. wscgrid : Pandas.Data.Frame() (time series) Water storage change grid in format 3D: [x, y, z, timestamp, value] or 1D: [z, timestamp, value]. boundary_values : str or float How to deal with the value for the LOWER boundary, if gcompgrid extents further than wscgrid. Possible values are 'extraplate' (default) or a float(value). boundary_up : str or float How to deal with the value for the UPPER boundary, if gcompgrid extents further than wscgrid. Possible values are str('lastvalue') or float(value to set). Returns ------ Pandas.DataFrame() [time series] Changes in gravity at gcompgrid sensor location in format [timestamps, value]. """ # ## set correct filling value for interpolation function if boundary_values == 'extrapolate': fill_value = None else: fill_value = boundary_values ## identify dimesion of input wsc grid # get column names of input data wsc_columns = wscgrid.columns # 3d if (("x" in wsc_columns) & ("y" in wsc_columns) & ("z" in wsc_columns)): print("Water storage change data given in 3D") wsc_dim = 3 # 1d if (("z" in wsc_columns) & ("x" not in wsc_columns) & ("y" not in wsc_columns)): print("Water storage change data given in 1D") wsc_dim = 1 if (("timestamp" not in wsc_columns) & ("datetime" not in wsc_columns)): print("No timeseries data supplied - calculating single gravity change") ## formatting data and prepare for interpolation # gcompgrid.rename(columns={"value": "gcomp"}) # wscgrid.rename(columns={"value": "wsc"}) # # check if gcompgrid extents more than wscgrid # this is probably mostly the case, at least for lower boundary ########### # for case: 1D input data if wsc_dim == 1: # get (static) target z-coordinates target_z = gcompgrid.z.unique() # get (static) 3d grid coordinates target_grid = pd.DataFrame({ 'x': gcompgrid.x, 'y': gcompgrid.y, 'z': gcompgrid.z, 'gcomp': gcompgrid.value }) # because this is only 1D, # target_grid gets reduced to z-dimension only target_grid = target_grid.groupby("z").gcomp.sum().to_frame().reset_index() ## # create result dataFrame gravity_response_ts = pd.DataFrame() # run through all timestamps of input data for timestamp_i in wscgrid.timestamp.unique(): # get input data data_z = wscgrid.loc[wscgrid.timestamp == timestamp_i, 'z'] data_value = wscgrid.loc[wscgrid.timestamp == timestamp_i, 'value'] # construct interpolation function i1d = interp1d(data_z, data_value, kind = "linear", bounds_error = False, fill_value = fill_value) # interpolate values target_value = i1d(target_z) # if using extrapolation: # if boundary_values == 'extrapolate': # make sure there are no negative values target_value[target_value < 0] = 0 ## spread 1d-values to matching z-coords for all (x, y) # construct interpolated dataframe wsc_target = pd.DataFrame({ 'z': target_z, 'wsc': target_value}) # join interpolated 1d values onto 3d grid wscInterpolated_temp = target_grid.join(wsc_target.set_index('z'), on='z') # ## calculate gravity response # in multiplying columns wscInterpolated_temp['value'] = wscInterpolated_temp['gcomp'] * wscInterpolated_temp['wsc'] gravity_response_value = wscInterpolated_temp['value'].sum() gravity_response_tmp = pd.DataFrame( {"timestamp" : [timestamp_i], "value" : [gravity_response_value] } ) # aggregating for each timestamp gravity_response_ts = pd.concat([gravity_response_ts, gravity_response_tmp]) gravity_response_ts.reset_index(drop=True, inplace = True) ########### # for case: 3D input data if wsc_dim == 3: # get (static) target z-coordinates target_x = gcompgrid.x target_y = gcompgrid.y target_z = gcompgrid.z target_points = (target_x, target_y, target_z) # get (static) 3d grid coordinates target_grid = pd.DataFrame({ 'x': gcompgrid.x, 'y': gcompgrid.y, 'z': gcompgrid.z, 'gcomp': gcompgrid.value }) # create result dataFrame gravity_response_ts = pd.DataFrame() # run through all timestamps of input data for timestamp_i in wscgrid.timestamp.unique(): # print(timestamp_i) # get input data data_x = wscgrid.loc[wscgrid.timestamp == timestamp_i, 'x'] data_y = wscgrid.loc[wscgrid.timestamp == timestamp_i, 'y'] data_z = wscgrid.loc[wscgrid.timestamp == timestamp_i, 'z'] data_points = (data_x, data_y, data_z) data_value = wscgrid.loc[wscgrid.timestamp == timestamp_i, 'value'] # construct interpolation function i3d = interpn(data_points, data_value, method = "linear", bounds_error = False, fill_value = fill_value) i3d = interpn(data_points, data_value, target_grid, method = "linear", bounds_error = False, fill_value = fill_value) # data_points # interpolate values target_grid_values = i3d(target_points) # if using extrapolation: # if boundary_values == 'extrapolate': # make sure there are no negative values target_grid_values[target_grid_values < 0] = 0 ## spread 1d-values to matching z-coords for all (x, y) # construct interpolated dataframe wsc_target = pd.DataFrame({ 'z': target_z, 'timestamp': timestamp_i, 'wsc': target_value}) # join interpolated 1d values onto 3d grid wscInterpolated_temp = target_grid.join(wsc_target.set_index('z'), on='z') ## calculate gravity response # in multiplying columns wscInterpolated_temp['value'] = wscInterpolated_temp['gcomp'] * wscInterpolated_temp['wsc'] gravity_response_value = wscInterpolated_temp['value'].sum() gravity_response_tmp = pd.DataFrame( {"timestamp" : [timestamp_i], "value" : [gravity_response_value] } ) # aggregating for each timestamp gravity_response_ts = pd.concat([gravity_response_ts, gravity_response_tmp]) gravity_response_ts.reset_index(drop=True, inplace = True) ########### print("Gravity response for provided time steps and storage changes calculated.") # return gravity_response_ts
# return gravity_response_ts, wscInterpolated