Skip to content

Commit c0356ff

Browse files
committed
Added a script to export FWI models to csv
1 parent c897a44 commit c0356ff

File tree

3 files changed

+113
-12
lines changed

3 files changed

+113
-12
lines changed

seismic/ASDFdatabase/FederatedASDFViewer.py

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
from scipy.stats import circmean as cmean
3333
from collections import defaultdict
3434
from shapely import geometry
35-
import traceback
35+
from seismic.misc import print_exception
3636

3737
class CustomPPSD(PPSD):
3838
def __init__(self, stats, skip_on_gaps=False,
@@ -134,13 +134,6 @@ def _plot_histogram(self, fig, draw=False, filename=None):
134134
return fig
135135
# end class
136136

137-
def printException(e: Exception):
138-
exc_type, exc_obj, exc_tb = sys.exc_info()
139-
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
140-
print(exc_type, e, fname, exc_tb.tb_lineno)
141-
print(traceback.format_exc())
142-
# end func
143-
144137
class FigureImage(gui.Image):
145138
def __init__(self, **kwargs):
146139
super(FigureImage, self).__init__("/%s/get_image_data?update_index=0" % id(self), **kwargs)
@@ -340,7 +333,7 @@ def setMapImage(nc, minLon=None, minLat=None, maxLon=None, maxLat=None):
340333
children['latBoundsBox'].children['max'].set_value(maxLat)
341334

342335
except Exception as e:
343-
printException(e)
336+
print_exception(e)
344337
# end try
345338
# end func
346339

@@ -552,7 +545,7 @@ def setTraceImage(nc, sc, lc, cc, st=None, et=None):
552545
ti = FigureImage(fig=fig)
553546
self.rowContainer.children[key].children['rightContainer'].children['plot'] = ti
554547
except Exception as e:
555-
printException(e)
548+
print_exception(e)
556549
# end try
557550
# end func
558551

@@ -612,7 +605,7 @@ def startStepChanged(emitter, value=None):
612605
args=(nc, sc, lc, cc, st, et))
613606
t.start()
614607
except Exception as e:
615-
printException(e)
608+
print_exception(e)
616609
# end try
617610
# end func
618611

@@ -627,7 +620,7 @@ def removeWidget(emitter):
627620
self.rowWidgetCount * ROW_WIDGET_HEIGHT * PADDING_FACTOR +
628621
MAP_WIDGET_PADDING)
629622
except Exception as e:
630-
printException(e)
623+
print_exception(e)
631624
# end try
632625
# end if
633626
# end func

seismic/ASDFdatabase/xdmf2csv.py

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
"""
2+
Description:
3+
Exports contents of XDMF to CSV.
4+
5+
References:
6+
7+
CreationDate: 02/05/24
8+
9+
10+
Revision History:
11+
LastUpdate: 02/05/24 RH
12+
"""
13+
14+
import click
15+
import vtk
16+
from vtk.numpy_interface import dataset_adapter as dsa
17+
import numpy as np
18+
from seismic.misc import print_exception
19+
import pyproj
20+
import pandas as pd
21+
import os
22+
23+
def tranforms_coords(x:np.ndarray, y:np.ndarray, z:np.ndarray) -> \
24+
(np.ndarray, np.ndarray, np.ndarray):
25+
26+
transformer = pyproj.Transformer.from_crs(
27+
{"proj": 'geocent', "ellps": 'WGS84', "datum": 'WGS84'},
28+
{"proj": 'latlong', "ellps": 'WGS84', "datum": 'WGS84'})
29+
30+
xyz2lonlatalt = lambda x, y, z: np.vstack(transformer.transform(x, y, z,
31+
radians=False)).T
32+
33+
result = xyz2lonlatalt(x, y, z)
34+
result[:, -1] *= -1 # convert to depth
35+
36+
return result[:, 0], result[:, 1], result[:, 2] # lons, lats, depths
37+
# end func
38+
39+
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
40+
@click.command(context_settings=CONTEXT_SETTINGS)
41+
@click.argument('input-file', required=True,
42+
type=click.Path(exists=True))
43+
@click.argument('output-folder', required=True,
44+
type=click.Path(exists=True))
45+
def process(input_file, output_folder):
46+
reader = vtk.vtkXdmfReader()
47+
48+
try:
49+
print('Reading input file: {}'.format(input_file))
50+
reader.SetFileName(input_file)
51+
reader.UpdateInformation()
52+
except Exception as e:
53+
print_exception(e)
54+
# end func
55+
56+
57+
pd2cd = vtk.vtkPointDataToCellData()
58+
pd2cd.SetInputConnection(reader.GetOutputPort())
59+
pd2cd.PassPointDataOn()
60+
61+
pd2cd.Update()
62+
63+
data = dsa.WrapDataObject(pd2cd.GetOutput())
64+
65+
data.PointData.keys()
66+
67+
xyz = data.GetPoints()
68+
69+
rkeys = ['VP', 'VSH', 'VSV']
70+
valsDict = {}
71+
72+
for key in rkeys:
73+
valsDict[key] = data.PointData[key]
74+
# end for
75+
76+
# tranform coordinates from geocentric xyz to geographic (both in wgs84)
77+
print('Transforming coordinates..')
78+
lons, lats, depths = tranforms_coords(xyz[:, 0], xyz[:, 1], xyz[:, 2])
79+
80+
# write csv
81+
ofn = os.path.splitext(os.path.basename(input_file))[0] + '.csv'
82+
ofn = os.path.join(output_folder, ofn)
83+
84+
df = pd.DataFrame()
85+
86+
df['lons'] = lons
87+
df['lats'] = lats
88+
df['depths_km'] = depths
89+
for key in rkeys:
90+
df[key] = valsDict[key]
91+
# end for
92+
93+
print('Writing output file: {}'.format(ofn))
94+
df.to_csv(ofn, header=True, index=False)
95+
# end func
96+
97+
98+
if __name__=="__main__":
99+
process()
100+
# end if

seismic/misc.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import os, glob, fnmatch, sys
1717
import numpy as np
1818
import logging
19+
import traceback
1920
logging.basicConfig()
2021

2122
def setup_logger(name, log_file=None, level=logging.INFO, propagate=False):
@@ -83,4 +84,11 @@ def rtp2xyz(r, theta, phi):
8384
xout[:, 1] = rst * np.sin(phi)
8485
xout[:, 2] = r * np.cos(theta)
8586
return xout
87+
# end func
88+
89+
def print_exception(e: Exception):
90+
exc_type, exc_obj, exc_tb = sys.exc_info()
91+
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
92+
print(exc_type, e, fname, exc_tb.tb_lineno)
93+
print(traceback.format_exc())
8694
# end func

0 commit comments

Comments
 (0)