def test_dtopo_io(): r"""Test IO of dtopography class""" test_data_path = os.path.join(testdir, "data", "alaska1964_test_data.tt3") test_dtopo = dtopotools.DTopography(path=test_data_path) temp_path = tempfile.mkdtemp() try: dtopo_paths = [ os.path.join(temp_path, 'alaska1964.tt1'), os.path.join(temp_path, 'alaska1964.tt3') ] # os.path.join(temp_path, 'alaska1964.tt2'), for path in dtopo_paths: test_dtopo.write(path) dtopo = dtopotools.DTopography(path=path) assert test_dtopo.dZ.shape == dtopo.dZ.shape, \ "Shape of dZ not equal for topo_type = %s." % dtopo.topo_type assert numpy.allclose(test_dtopo.dZ, dtopo.dZ), \ "dZ not equal for %s" % path except AssertionError as e: test_dump_path = os.path.join(os.getcwd(), "test_dtopo_io") shutil.mkdir(test_dump_path) shutil.copy(temp_path, test_dump_path) raise e finally: shutil.rmtree(temp_path)
def create_dtopo(location, scenario_name, N=100, estimate_mass=True, force=False, plot=False, topo_path=None): scenario = locations[location]["scenarios"][scenario_name] extent = locations[location]['extent'] path = os.path.join("..", location, "%s.tt3" % scenario_name) if os.path.exists(path): if force: os.remove(path) else: print("Slide file already exists.") sys.exit(0) # Create dtopo dtopo = dt.DTopography() dtopo.x = numpy.linspace(extent[0], extent[1], N) dtopo.y = numpy.linspace(extent[2], extent[3], N) dtopo.X, dtopo.Y = numpy.meshgrid(dtopo.x, dtopo.y) dtopo.times = numpy.linspace(0, scenario['t_end'], 8) dtopo.dZ = numpy.empty((dtopo.times.shape[0], dtopo.x.shape[0], dtopo.y.shape[0])) for (i, t) in enumerate(dtopo.times): dtopo.dZ[i, :, :] = slide_topo(dtopo.X, dtopo.Y, t, scenario["start"], scenario["slide_speed"], scenario["max_length"], scenario["theta"], scenario["sigma"], scenario["A"], estimate_mass=estimate_mass) dtopo.write(path=path) if plot: # Load topo for comparison topo = tt.Topography(path=locations[location]["topo_path"], topo_type=3) if not os.path.exists("./%s" % scenario_name): os.mkdir(scenario_name) for i in range(dtopo.times.shape[0] - 1, -1, -1): fig = plt.figure() axes = fig.add_subplot(1, 1, 1) extent = [numpy.min(dtopo.x), numpy.max(dtopo.x), numpy.min(dtopo.y), numpy.max(dtopo.y)] axes.pcolor(dtopo.x, dtopo.y, dtopo.dZ_at_t(dtopo.times[i])) axes.contour(topo.x, topo.y, topo.Z, levels=[5000], colors='w') axes.set_xlim(extent[:2]) axes.set_ylim(extent[2:]) axes.set_title("t = %s" % str(dtopo.times[i])) fig.savefig('./%s/slide_%s.png' % (scenario_name, i)) # make a movie cmd = r"ffmpeg -r 2 -i %s" % scenario_name + r"/slide_%1d.png " + \ r"-q:a 0 -q:v 0 -vcodec mpeg4 -vb 20M -r 24 %s/%s.mp4" % (scenario_name, scenario_name) subprocess.call(cmd, shell=True)
def plot_dtopo(plotdata): print "Creating html for other figures." with open('fault.html', 'w') as out_html: out_html.write("<html>\n") out_html.write(" <header>\n") out_html.write(" <title>Fault Specification</title>\n") out_html.write(" </header>\n") out_html.write(" <body>\n") out_html.write(" <h1>Fault Specification</h1>\n") out_html.write(" <img src='fault.png'>\n") out_html.write(" <img src='uplift.png'>\n") out_html.write(" </body>\n") out_html.write("</html>") # Need to save this in the run_faults section, cannot do yet # fault = dtopotools.Fault(path="./fault_params.txt") # fig = plt.figure() # axes = fig.add_subplot(1, 1, 1) # fault.plot_subfaults(axes, slip_color=True, cmin_slip=0.0, # cmax_slip=120.0) # fig.savefig('fault.png') dtopo = dtopotools.DTopography(path=dtopo_data.dtopofiles[0][3]) fig = plt.figure() axes = fig.add_subplot(1, 1, 1) dtopo.plot_dZ_colors(t=1.0, axes=axes) fig.savefig("uplift.png")
def make_dtopo(makeplots=False): """ Create dtopo data file for deformation of sea floor due to earthquake. Uses the Okada model with fault parameters and mesh specified below. """ from clawpack.geoclaw import dtopotools import numpy dtopo_fname = 'AASZ04v2.tt3' url = 'http://students.washington.edu/bndavis/misc/dtopo/alaska/' + dtopo_fname clawpack.clawutil.data.get_remote_file(url, output_dir=scratch_dir, file_name=dtopo_fname, verbose=True) if makeplots: from matplotlib import pyplot as plt if fault.dtopo is None: # read in the pre-existing file: print "Reading in dtopo file..." dtopo = dtopotools.DTopography() dtopo.read(dtopo_fname, dtopo_type=3) x = dtopo.x y = dtopo.y plt.figure(figsize=(12,7)) ax1 = plt.subplot(121) ax2 = plt.subplot(122) fault.plot_subfaults(axes=ax1,slip_color=True) ax1.set_xlim(x.min(),x.max()) ax1.set_ylim(y.min(),y.max()) dtopo.plot_dz_colors(1.,axes=ax2) fname = os.path.splitext(dtopo_fname)[0] + '.png' plt.savefig(fname) print "Created ",fname
def test_SubdividedPlaneFault_make_dtopo(save=False): r"""""" # get a unit source fault plane as starting point: sift_slip = {'acsza1': 1.} fault = dtopotools.SiftFault(sift_slip) fault_plane = fault.subfaults[0] # Mo = fault_plane.Mo() # print "original Mo = ",Mo fault2 = dtopotools.SubdividedPlaneFault(fault_plane, nstrike=5, ndip=3) # print "new Mo = ",fault2.Mo() #fault2.plot_subfaults(slip_color=True) assert abs(fault2.Mw() - 6.83402) < 1e-4, \ "*** Mw is wrong: %g" % fault.Mw() xlower = 162. xupper = 168. ylower = 53. yupper = 59. # dtopo parameters: points_per_degree = 4 # 15 minute resolution dx = 1. / points_per_degree mx = int((xupper - xlower) / dx + 1) xupper = xlower + (mx - 1) * dx my = int((yupper - ylower) / dx + 1) yupper = ylower + (my - 1) * dx x = numpy.linspace(xlower, xupper, mx) y = numpy.linspace(ylower, yupper, my) times = [1.] dtopo = fault2.create_dtopography(x, y, times) test_data_path = os.path.join(testdir, "data", "SubdividedFaultPlane_test_data.tt3") if save: dtopo.write(test_data_path, dtopo_type=3) compare_data = dtopotools.DTopography(path=test_data_path) compare_data.read(path=test_data_path, dtopo_type=3) assert dtopo.dZ.shape == compare_data.dZ.shape, \ "dtopo.dZ.shape is %s, should be %s" \ % (dtopo.dZ.shape, compare_data.dZ.shape) assert numpy.allclose(compare_data.dZ, dtopo.dZ)
def test_read_csv_make_dtopo(save=False): r"""Test reading and making of a CSV subfault speficied dtopo.""" subfault_path = os.path.join(testdir, 'data', 'alaska1964.csv') input_units = { "length": "km", "width": "km", "depth": "km", "slip": "m", "mu": "dyne/cm^2" } fault = dtopotools.CSVFault() fault.read(subfault_path, input_units=input_units, coordinate_specification="noaa sift") assert abs(fault.Mw() - 8.53336) < 1e-4, "*** Mw is wrong: %g" % fault.Mw() xlower = 203 xupper = 214. # approximate - adjusted below ylower = 55 yupper = 60. # approximate - adjusted below # dtopo parameters: points_per_degree = 4 # 15 minute resolution dx = 1. / points_per_degree mx = int((xupper - xlower) / dx + 1) xupper = xlower + (mx - 1) * dx my = int((yupper - ylower) / dx + 1) yupper = ylower + (my - 1) * dx x = numpy.linspace(xlower, xupper, mx) y = numpy.linspace(ylower, yupper, my) dtopo = fault.create_dtopography(x, y, times=[1.]) test_data_path = os.path.join(testdir, "data", "alaska1964_test_data.tt3") if save: dtopo.write(test_data_path, dtopo_type=3) compare_data = dtopotools.DTopography(path=test_data_path) compare_data.read(path=test_data_path, dtopo_type=3) assert dtopo.dZ.shape == compare_data.dZ.shape, \ "dtopo.dZ.shape is %s, should be %s" \ % (dtopo.dZ.shape, compare_data.dZ.shape) assert numpy.allclose(compare_data.dZ, dtopo.dZ)
def test_read_ucsb_make_dtopo(save=False): r"""Test reading and making of a UCSB subfault speficied dtopo.""" subfault_path = os.path.join(testdir, 'data', 'tohoku_ucsb.txt') fault = dtopotools.UCSBFault() fault.read(subfault_path) assert abs(fault.Mw() - 9.13957973) < 1e-4, "*** Mw is wrong: %g" % fault.Mw() xlower = 140. xupper = 146. ylower = 35. yupper = 41. # dtopo parameters: points_per_degree = 4 # 15 minute resolution dx = 1. / points_per_degree mx = int((xupper - xlower) / dx + 1) xupper = xlower + (mx - 1) * dx my = int((yupper - ylower) / dx + 1) yupper = ylower + (my - 1) * dx x = numpy.linspace(xlower, xupper, mx) y = numpy.linspace(ylower, yupper, my) tmax = 0. for s in fault.subfaults: tmax = max(tmax, s.rupture_time + s.rise_time + s.rise_time_ending) fault.rupture_type = 'dynamic' times = numpy.linspace(0, tmax, 10) dtopo = fault.create_dtopography(x, y, times) test_data_path = os.path.join(testdir, "data", "tohoku_test_data.tt3") if save: dtopo.write(test_data_path, dtopo_type=3) compare_data = dtopotools.DTopography(path=test_data_path) compare_data.read(path=test_data_path, dtopo_type=3) assert dtopo.dZ.shape == compare_data.dZ.shape, \ "dtopo.dZ.shape is %s, should be %s" \ % (dtopo.dZ.shape, compare_data.dZ.shape) assert numpy.allclose(compare_data.dZ, dtopo.dZ)
def dtopo2kml(dtopo_file_name, dtopo_type, color='8888FF'): """ Create a kml file putting a box around the region covered by a dtopofile. Color is pink by default. """ import os from clawpack.geoclaw import dtopotools dtopo = dtopotools.DTopography() dtopo.read(dtopo_file_name, dtopo_type) x1 = dtopo.x.min() x2 = dtopo.x.max() y1 = dtopo.y.min() y2 = dtopo.y.max() xy = (x1, x2, y1, y2) name = os.path.splitext(os.path.split(dtopo_file_name)[-1])[0] file_name = '%s.kml' % name box2kml(xy, file_name, name, color)
def interp_dz(self,dtopo_path,dtopo_type): """ Compute approximate values of deformation dz on X,Y grid using a specified dtopo file. Also calculates B0 = B - dz, attempting to recover the pre-event topography from the GeoClaw run topography stored in B. """ from clawpack.geoclaw import dtopotools from scipy.interpolate import RegularGridInterpolator dtopo = dtopotools.DTopography(dtopo_path, dtopo_type=dtopo_type) x1d = dtopo.X[0,:] y1d = dtopo.Y[:,0] dtopo_func = RegularGridInterpolator((x1d,y1d), dtopo.dZ[-1,:,:].T, method='linear', bounds_error=False, fill_value=0.) dz = dtopo_func(list(zip(numpy.ravel(self.X), numpy.ravel(self.Y)))) self.dz = numpy.reshape(dz, self.X.shape) print('Over fgmax extent, min(dz) = %.2f m, max(dz) = %.2f m' \ % (dz.min(), dz.max()))
def test_read_sift_make_dtopo(save=False): r"""Test reading and making of a SIFT subfault speficied dtopo""" sift_slip = {'acsza1': 2, 'acszb1': 3} fault = dtopotools.SiftFault(sift_slip) assert abs(fault.Mw() - 7.966666666667) < 1e-4, "*** Mw is wrong: %g" % fault.Mw() xlower = 162. xupper = 168. ylower = 53. yupper = 59. # dtopo parameters: points_per_degree = 4 # 15 minute resolution dx = 1. / points_per_degree mx = int((xupper - xlower) / dx + 1) xupper = xlower + (mx - 1) * dx my = int((yupper - ylower) / dx + 1) yupper = ylower + (my - 1) * dx x = numpy.linspace(xlower, xupper, mx) y = numpy.linspace(ylower, yupper, my) times = [1.] dtopo = fault.create_dtopography(x, y, times) test_data_path = os.path.join(testdir, "data", "sift_test_data.tt3") if save: dtopo.write(test_data_path, dtopo_type=3) compare_data = dtopotools.DTopography(path=test_data_path) compare_data.read(path=test_data_path, dtopo_type=3) assert dtopo.dZ.shape == compare_data.dZ.shape, \ "dtopo.dZ.shape is %s, should be %s" \ % (dtopo.dZ.shape, compare_data.dZ.shape) assert numpy.allclose(compare_data.dZ, dtopo.dZ)
def make_dtopo(makeplots=False): """ Create dtopo data file for deformation of sea floor due to earthquake. Uses the Okada model with fault parameters and mesh specified below. """ from clawpack.geoclaw import dtopotools import numpy dtopo_fname = os.path.join(scratch_dir, "dtopo_usgs100227.tt3") # Specify subfault parameters for this simple fault model consisting # of a single subfault: usgs_subfault = dtopotools.SubFault() usgs_subfault.strike = 16. usgs_subfault.length = 450.e3 usgs_subfault.width = 100.e3 usgs_subfault.depth = 35.e3 usgs_subfault.slip = 15. usgs_subfault.rake = 104. usgs_subfault.dip = 14. usgs_subfault.longitude = -72.668 usgs_subfault.latitude = -35.826 usgs_subfault.coordinate_specification = "top center" fault = dtopotools.Fault() fault.subfaults = [usgs_subfault] print "Mw = ", fault.Mw() if os.path.exists(dtopo_fname): print "*** Not regenerating dtopo file (already exists): %s" \ % dtopo_fname else: print "Using Okada model to create dtopo file" x = numpy.linspace(-77, -67, 100) y = numpy.linspace(-40, -30, 100) times = [1.] fault.create_dtopography(x, y, times) dtopo = fault.dtopo dtopo.write(dtopo_fname, dtopo_type=3) if makeplots: from matplotlib import pyplot as plt if fault.dtopo is None: # read in the pre-existing file: print "Reading in dtopo file..." dtopo = dtopotools.DTopography() dtopo.read(dtopo_fname, dtopo_type=3) x = dtopo.x y = dtopo.y plt.figure(figsize=(12, 7)) ax1 = plt.subplot(121) ax2 = plt.subplot(122) fault.plot_subfaults(axes=ax1, slip_color=True) ax1.set_xlim(x.min(), x.max()) ax1.set_ylim(y.min(), y.max()) dtopo.plot_dZ_colors(1., axes=ax2) fname = os.path.splitext(os.path.split(dtopo_fname)[-1])[0] + '.png' plt.savefig(fname) print "Created ", fname
""" Set up the plot figures, axes, and items to be done for each frame. This module is imported by the plotting routines and then the function setplot is called to set the plot parameters. """ from __future__ import absolute_import import numpy from clawpack.geoclaw import dtopotools dtopo1 = dtopotools.DTopography('dtopo1.tt3', 3) dtopo2 = dtopotools.DTopography('dtopo2.tt3', 3) #-------------------------- def setplot(plotdata): #-------------------------- """ Specify what is to be plotted at each frame. Input: plotdata, an instance of pyclaw.plotters.data.ClawPlotData. Output: a modified version of plotdata. """ from clawpack.visclaw import colormaps, geoplot plotdata.clearfigures() # clear any old figures,axes,items data # To plot gauge locations on pcolor or contour plot, use this as
def make_dtopo(params, makeplots=False): """ Create dtopo data file for deformation of sea floor due to earthquake. Uses the Okada model with fault parameters and mesh specified below. """ dtopo_fname = os.path.join('./InputData/', "dtopo.tt3") # number of cols = number of rectangles * number of changing params + number of constant params n = (len(params) - 4) // 5 # Specify subfault parameters for this simple fault model consisting # of a single subfault: subfaults = [] for i in range(n): usgs_subfault = dtopotools.SubFault() usgs_subfault.strike = params['Strike' + str(i + 1)] usgs_subfault.length = params['Sublength'] usgs_subfault.width = params['Subwidth'] usgs_subfault.depth = params['Depth' + str(i + 1)] usgs_subfault.slip = params['Slip'] usgs_subfault.rake = params['Rake'] usgs_subfault.dip = params['Dip' + str(i + 1)] usgs_subfault.longitude = params['Longitude' + str(i + 1)] usgs_subfault.latitude = params['Latitude' + str(i + 1)] usgs_subfault.coordinate_specification = "centroid" subfaults.append(usgs_subfault) fault = dtopotools.Fault() fault.subfaults = subfaults print(fault.subfaults) print("Mw = ", fault.Mw()) print("Mo = ", fault.Mo()) if os.path.exists(dtopo_fname): print("*** Not regenerating dtopo file (already exists): %s" \ % dtopo_fname) else: print("Using Okada model to create dtopo file") #x = numpy.linspace(-77, -67, 100) #y = numpy.linspace(-40, -30, 100) times = [1.] with open('./PreRun/InputData/model_bounds.txt') as json_file: model_bounds = json.load(json_file) xlower = model_bounds['xlower'] xupper = model_bounds['xupper'] ylower = model_bounds['ylower'] yupper = model_bounds['yupper'] # dtopo parameters points_per_degree = 60 # 1 minute resolution dx = 1. / points_per_degree mx = int((xupper - xlower) / dx + 1) xupper = xlower + (mx - 1) * dx my = int((yupper - ylower) / dx + 1) yupper = ylower + (my - 1) * dx print("New upper bounds:\n") print("latitude:", yupper) print("longitude:", xupper) x = np.linspace(xlower, xupper, mx) y = np.linspace(ylower, yupper, my) fault.create_dtopography(x, y, times, verbose=True) dtopo = fault.dtopo dtopo.write(dtopo_fname, dtopo_type=3) if makeplots: from matplotlib import pyplot as plt if fault.dtopo is None: # read in the pre-existing file: print("Reading in dtopo file...") dtopo = dtopotools.DTopography() dtopo.read(dtopo_fname, dtopo_type=3) x = dtopo.x y = dtopo.y plt.figure(figsize=(12, 7)) ax1 = plt.subplot(121) ax2 = plt.subplot(122) fault.plot_subfaults(axes=ax1, slip_color=True) ax1.set_xlim(x.min(), x.max()) ax1.set_ylim(y.min(), y.max()) dtopo.plot_dZ_colors(1., axes=ax2) fname = os.path.splitext(os.path.split(dtopo_fname)[-1])[0] + '.png' plt.savefig(fname) print("Created ", fname)