Beispiel #1
0
def test_tr(grids=[1800, 3600, 7200], frame=2):
    reload(setrun)
    errs = []

    for i, mx in enumerate(grids):
        print i, mx
        rundata = setrun.setrun()

        rundata.probdata.trtime = 600.
        rundata.probdata.t1 = 10.
        rundata.probdata.a1 = 0.1
        rundata.probdata.tw1 = 10.

        rundata.clawdata.mx = mx
        rundata.clawdata.tfinal = 1200.
        rundata.clawdata.nout = 60
        rundata.write()
        runclaw(xclawcmd='xsclaw', outdir='./_output')

        exact, approx, xc = timereverse(frame=frame)

        Linf_err = max(abs(approx - exact))
        print mx, Linf_err

        errs.append(Linf_err)

    return grids, errs
    def __init__(self, run_number=1, wave_tolerance=1.0, deep_depth=300.0):

        super(SweepJob, self).__init__(time=720)

        self.omp_num_threads = 16

        self.run_number = run_number
        self.type = 'sweep'
        self.name = 'wave_deep_01'
        self.prefix = 'run_%s_wave_%s_deep_%s' % (self.run_number,
                                                  wave_tolerance, deep_depth)
        self.executable = 'xgeoclaw'

        self.group = 'yetiapam'

        import setrun
        self.rundata = setrun.setrun()

        # incorporate storm parameters
        self.rundata.add_data(surge.SurgeData(), 'stormdata')
        setrun.set_storm(self.rundata)
        self.rundata.add_data(surge.FrictionData(), 'frictiondata')
        setrun.set_friction(self.rundata)

        ### modify setrun parameters here ###
        refine_data = self.rundata.refinement_data
        refine_data.wave_tolerance = wave_tolerance
        refine_data.deep_depth = deep_depth
Beispiel #3
0
    def __init__(self):
        r"""
        Initialize a FidelityJob object.

        See :class:`FidelityJob` for full documentation

        """

        super(FidelityJob, self).__init__()

        self.type = "bowl-radial"
        self.name = "fidelity-test"
        self.prefix = "fault_%s" % self.run_number
        self.executable = 'xgeoclaw'

        # Data objects
        import setrun
        self.rundata = setrun.setrun()

        # No variable friction for the time being
        self.rundata.friction_data.variable_friction = False

        # Replace dtopo file with our own
        self.dtopo_path = 'fault_s%s.tt3' % self.base_subfault.slip
        self.rundata.dtopo_data.dtopofiles = [[3, 4, 4, self.dtopo_path]]
Beispiel #4
0
    def __init__(self, fault, name=""): 
        r"""
        Initialize a FaultJob object.
        
        See :class:`FaultJob` for full documentation
        
        """ 

        super(FaultJob, self).__init__()

        self.type = "tsunami"
        self.name = "final-tohoku-inversions"
        self.prefix = "fault_%s" % name
        self.executable = 'xgeoclaw'

        # Data objects
        import setrun
        self.rundata = setrun.setrun()

        # No variable friction for the time being
        self.rundata.friction_data.variable_friction = False

        # Replace dtopo file with our own
        self.dtopo_path = 'fault_%s.tt3' % name
        self.rundata.dtopo_data.dtopofiles = [[3, 4, 4, self.dtopo_path]]

        self.fault = fault
Beispiel #5
0
    def runTest(self):

        # Write out data files
        orig_path = os.getcwd()
        if sys.modules.has_key('setrun'):
            del(sys.modules['setrun'])
        sys.path.insert(0, self.test_path)
        import setrun
        rundata = setrun.setrun()
        os.chdir(self.temp_path)
        rundata.write()
        os.chdir(orig_path)
        sys.path.pop(0)

        # Run code
        runclaw_cmd = " ".join((
                            "cd %s ;" % self.temp_path,
                            "python",
                            "$CLAW/clawutil/src/python/clawutil/runclaw.py",
                            "xgeoclaw",
                            self.temp_path,
                            "True",
                            "False",
                            self.temp_path))
        subprocess.check_call(runclaw_cmd, stdout=self.stdout, 
                                           stderr=self.stderr,
                                           shell=True)
        self.stdout.flush()
        self.stderr.flush()
Beispiel #6
0
def test_tr(grids=[1800,3600,7200],frame=2):
    reload(setrun)
    errs = []

    for i,mx in enumerate(grids):
        print i,mx
        rundata=setrun.setrun()

        rundata.probdata.trtime=600.
        rundata.probdata.t1= 10.
        rundata.probdata.a1= 0.1
        rundata.probdata.tw1=10.

        rundata.clawdata.mx=mx
        rundata.clawdata.tfinal=1200.
        rundata.clawdata.nout=60
        rundata.write()
        runclaw(xclawcmd='xsclaw',outdir='./_output')

        exact,approx,xc = timereverse(frame=frame)

        Linf_err = max(abs(approx-exact))
        print mx, Linf_err

        errs.append(Linf_err)

    return grids,errs
Beispiel #7
0
def create_data(casepath):
    """Create *.data files in a case folder."""

    if not os.path.isdir(casepath):
        logger.error("Case folder %s not found.", casepath)
        raise FileNotFoundError("Case folder {} not found.".format(casepath))

    setrunpath = os.path.join(casepath, "setrun.py")
    if not os.path.isfile(setrunpath):
        logger.error("Case folder % does not have setrun.py.", casepath)
        raise FileNotFoundError(
            "Case folder {} does not have setrun.py.".format(casepath))

    pwd = os.getcwd()  # get current working directory
    os.chdir(casepath)  # go to case folder

    if casepath != sys.path[0]:
        sys.path.insert(0, casepath)  # add case folder to module search path
    import setrun  # import the setrun.py
    rundata = setrun.setrun()  # get ClawRunData object
    rundata.write()  # write *.data to the case folder
    del rundata
    del sys.modules["setrun"]
    del sys.path[0]

    os.chdir(pwd)  # go back to pwd
Beispiel #8
0
    def __init__(self, index, values, 
                       source_path='$SRC/tohoku2011-paper1/sources/Ammon.txydz',
                       contours=(numpy.infty,0.0,-200.0,-numpy.infty)):
        r""""""

        super(FrictionJob, self).__init__()

        self.source_path = os.path.expandvars(source_path)

        self.type = "tohoku"
        self.name = "friction-sensitivity-%s" % \
                        os.path.split(os.path.splitext(self.source_path)[0])[-1]
        self.prefix = "fric_%s" % (str(index))
        self.executable = 'xgeoclaw'

        # Data objects
        import setrun
        self.rundata = setrun.setrun()

        # Set variable friction
        self.rundata.friction_data.variable_friction = True

        # Region based friction
        self.rundata.friction_data.friction_regions = [[
                       self.rundata.clawdata.lower, self.rundata.clawdata.upper,
                       contours, values]]

        # Set earthquake source model
        dtopo_data = self.rundata.dtopo_data
        dtopo_data.dtopofiles.append([1, 4, 4, self.source_path])
Beispiel #9
0
    def __init__(self,
                 index,
                 values,
                 source_path='$SRC/tohoku2011-paper1/sources/Ammon.txydz',
                 contours=(numpy.infty, 0.0, -200.0, -numpy.infty)):
        r""""""

        super(FrictionJob, self).__init__()

        self.source_path = os.path.expandvars(source_path)

        self.type = "tohoku"
        self.name = "friction-sensitivity-%s" % \
                        os.path.split(os.path.splitext(self.source_path)[0])[-1]
        self.prefix = "fric_%s" % (str(index))
        self.executable = 'xgeoclaw'

        # Data objects
        import setrun
        self.rundata = setrun.setrun()

        # Set variable friction
        self.rundata.friction_data.variable_friction = True

        # Region based friction
        self.rundata.friction_data.friction_regions = [[
            self.rundata.clawdata.lower, self.rundata.clawdata.upper, contours,
            values
        ]]

        # Set earthquake source model
        dtopo_data = self.rundata.dtopo_data
        dtopo_data.dtopofiles.append([1, 4, 4, self.source_path])
    def __init__(self, index, values, 
                       source_path='clawpack/geoclaw/examples/tsunami/chile2010'):
        r""""""

        super(LevelsJob, self).__init__()

        self.source_path = os.path.expandvars(source_path)

        self.type = "Run_Data"
        self.name = "AMR-Levels-%s" % \
                        os.path.split(os.path.splitext(self.source_path)[0])[-1]
        self.prefix = "sweep_%s" % (str(index))
        self.executable = 'xgeoclaw'

        # Data objects
        import setrun
        self.rundata = setrun.setrun()
        
        values = [int(i) for i in values]
        # Geo Claw Number of Cells Data
        self.rundata.clawdata.num_cells = [values[0],values[0]]

        # AMR Data max levels and refinement ratios
        self.rundata.amrdata.amr_levels_max = values[1]
        self.rundata.amrdata.refinement_ratios_x = values[2:]
        self.rundata.amrdata.refinement_ratios_y = values[2:]
        self.rundata.amrdata.refinement_ratios_t = values[2:]
def create_data(casepath):
    """Create *.data files (and topography & hydrological files) in case folder.

    Args:
        casepath [in]: a string indicating the abs path of case folder.
    """
    import createtopo
    import createhydro

    if not os.path.isdir(casepath):
        print("Error: case folder {} does not exist.".format(casepath),
              file=sys.stderr)
        sys.exit(1)

    setrunpath = os.path.join(casepath, "setrun.py")
    if not os.path.isfile(setrunpath):
        print("Error: case folder {} does not have setrun.py.".format(casepath),
              file=sys.stderr)
        sys.exit(1)

    sys.path.insert(0, casepath) # add case folder to module search path
    import setrun # import the setrun.py

    pwd = os.getcwd() # get current working directory
    os.chdir(casepath) # go to case folder
    rundata = setrun.setrun() # get ClawRunData object
    rundata.write() # write *.data to the case folder
    os.chdir(pwd) # go back to pwd

    # check if topo file exists. Download it if not exist
    createtopo.check_download_topo(casepath, rundata)

    # check if hudro file exists. Download it if not exist
    createhydro.check_download_hydro(casepath, rundata)
Beispiel #12
0
 def __init__(self):
     super(TestML1D,self).__init__()
     
     import setrun
     
     self.run_data = setrun.setrun()
     self.ml_data = setrun.set_multilayer_data()
     
     self.type = "ml_1d"
Beispiel #13
0
def fgmax2kml(rundata=None,
              fname='fgmax_grids.kml',
              verbose=True,
              combined=False):
    """
    Create a KML box for each fgmax grid specified for a GeoClaw run.

    :Inputs:

      - *rundata* - an object of class *ClawRunData* or None

        If *rundata==None*, try to create based on executing function *setrun*
        from the `setrun.py` file in the current directory.

      - *fname* (str) - resulting kml file.

      - *verbose* (bool) - If *True*, print out info about each region found

      - *combined* (bool) - If *True*, combine into single kml file with
        name given by *fname*.  NOT YET IMPLEMENTED.
        If False, *fname* is ignored and individual files are created for
        each fgmax grid.

    """

    from numpy import cos, pi, floor

    if rundata is None:
        try:
            import setrun
            reload(setrun)
            rundata = setrun.setrun()
        except:
            raise IOError("*** cannot execute setrun file")

    if combined:
        fname_combined = 'fgmax_grids.kml'
        print('*** combined fgmax kml files not yet supported')
        print('    making a kml file for each fgmax grid')

    fgmax_grids = rundata.fgmax_data.fgmax_grids

    for fg in fgmax_grids:
        fname_root = 'fgmax%s' % str(fg.fgno).zfill(4)
        kml_file = fname_root + '.kml'
        if fg.point_style == 1:
            xy = ([fg.x1, fg.x2], [fg.y1, fg.y2])
            line2kml(xy, kml_file, fname_root, color='8888FF', width=2)
        if fg.point_style == 2:
            xy = ([fg.x1, fg.x2], [fg.y1, fg.y2])
            box2kml(xy, kml_file, fname_root, color='8888FF')
        elif fg.point_style == 3:
            xy = ([fg.x1, fg.x2, fg.x3, fg.x4], [fg.y1, fg.y2, fg.y3, fg.y4])
            poly2kml(xy, kml_file, fname_root, color='8888FF')
        else:
            print('fgmax2kml not yet implemented for point_style = %i' \
                  % fg.point_style)
Beispiel #14
0
def getent(K, rho):
    rundata = setrun.setrun()
    rundata.probdata.K_B = K
    rundata.probdata.rho_B = rho
    print K, rho
    rundata.write()
    runclaw(outdir='./_output')

    ent = entropy(rundata.clawdata.nout)
    return ent[-1]
Beispiel #15
0
def getent(K,rho):
  rundata=setrun.setrun()
  rundata.probdata.K_B=K
  rundata.probdata.rho_B=rho
  print K,rho
  rundata.write()
  runclaw(outdir='./_output')

  ent=entropy(rundata.clawdata.nout)
  return ent[-1]
Beispiel #16
0
 def __init__(self):
     super(TestML2D,self).__init__()
     
     import setrun
 
     self.run_data = setrun.setrun()
     self.ml_data = setrun.set_multilayer_data()
     self.hurricane_data = setrun.set_hurricane_data()
     
     self.type = "ml_2d"
Beispiel #17
0
def create_volume_datafile(casepath):
    """Create a volume.csv for a case."""
    import numpy

    casepath = os.path.abspath(casepath)
    out_path = os.path.join(casepath, "_output")
    repo_path = os.path.dirname(os.path.abspath(__file__))
    claw_path = os.path.join(repo_path, "src", "clawpack-v5.5.0")

    logger.info("Creating total volume datafile for case %s", casepath)
    if os.path.isfile(os.path.join(casepath, "volume.csv")):
        logger.warning("%s exists. Skip.", os.path.join(casepath, "volume.csv"))
        logger.handlers[0].flush()
        logger.handlers[1].flush()
        return

    # add environment variables
    os.environ["CLAW"] = claw_path

    # add clawpack python package search path
    if claw_path != sys.path[0]:
        sys.path.insert(0, claw_path)

    # import utilities
    from clawpack import pyclaw

    # get # of frames from setrun.py
    if casepath != sys.path[0]:
        sys.path.insert(0, casepath)
    import setrun # import the setrun.py
    rundata = setrun.setrun() # get ClawRunData object
    nframes = rundata.clawdata.num_output_times + 1
    nlevels = rundata.amrdata.amr_levels_max
    del rundata
    del sys.modules["setrun"]
    del sys.path[0]

    data = numpy.zeros((nframes, 1+nlevels), dtype=numpy.float64)
    for fno in range(0, nframes):
        # empty solution object
        soln = pyclaw.Solution()

        # read
        soln.read(fno, out_path, file_format="binary", read_aux=False)

        # calculate total volume at each grid level
        data[fno, 0] = soln.state.t
        data[fno, 1:] = get_volumes_single_frame(nlevels, soln)

    numpy.savetxt(os.path.join(casepath, "volume.csv"), data, delimiter=",")
    logger.info("Done creating total volume datafile.")
    logger.handlers[0].flush()
    logger.handlers[1].flush()
Beispiel #18
0
    def load_rundata(self):
        r"""(Re)load setrun module and create *rundata* object


        """

        if sys.modules.has_key('setrun'):
            del (sys.modules['setrun'])
        sys.path.insert(0, self.test_path)
        import setrun
        self.rundata = setrun.setrun()
        sys.path.pop(0)
Beispiel #19
0
    def load_rundata(self):
        r"""(Re)load setrun module and create *rundata* object


        """

        if 'setrun' in sys.modules:
            del(sys.modules['setrun'])
        sys.path.insert(0, self.test_path)
        import setrun
        self.rundata = setrun.setrun()
        sys.path.pop(0)
    def __init__(self, levels=3):
        super(SwirlTest, self).__init__()

        self.type = "AMRClaw"
        self.name = "swirl"
        self.setplot = "setplot"

        # Data objects
        import setrun
        self.rundata = setrun.setrun()

        self.rundata.amrdata.amr_levels_max = levels
    def __init__(self, levels=3):
        super(SwirlTest, self).__init__()

        self.type = "AMRClaw"
        self.name = "swirl"
        self.setplot = "setplot"

        # Data objects
        import setrun
        self.rundata = setrun.setrun()

        self.rundata.amrdata.amr_levels_max = levels
Beispiel #22
0
    def load_rundata(self):
        r"""(Re)load setrun module and create *rundata* object


        """

        if sys.modules.has_key("setrun"):
            del (sys.modules["setrun"])
        sys.path.insert(0, self.test_path)
        import setrun

        self.rundata = setrun.setrun()
        sys.path.pop(0)
Beispiel #23
0
def gauges2kml(rundata=None, fname='gauges.kml'):

    """
    Read in the gauge locations from setrun.py and create a kml point for each.
    """


    if rundata is None:
        try:
            import setrun
            reload(setrun)
            rundata = setrun.setrun()
        except:
            raise IOError("*** cannot execute setrun file")

    elev = 0.
    kml_text = kml_header()
    

    gauges = rundata.gaugedata.gauges
    if len(gauges)==0:
        print "No gauges found in setrun.py"


    for rnum,gauge in enumerate(gauges):
        t1,t2 = gauge[3:5]
        x1,y1 = gauge[1:3]
        gaugeno = gauge[0]
        print "Gauge %i: %10.6f  %10.6f  \n" % (gaugeno,x1,y1) \
                + "  t1 = %10.1f,  t2 = %10.1f" % (t1,t2)
        mapping = {}
        mapping['gaugeno'] = gaugeno
        mapping['t1'] = t1
        mapping['t2'] = t2
        mapping['x1'] = x1
        mapping['y1'] = y1
        mapping['elev'] = elev
        mapping['name'] = 'Gauge %i' % rnum
        description = "  t1 = %g, t2 = %g\n" % (t1,t2) \
            + "  x1 = %g, y1 = %g\n" % (x1,y1)
        mapping['desc'] = description

        gauge_text = kml_gauge(mapping)
        kml_text = kml_text + gauge_text
    kml_text = kml_text + kml_footer()
    kml_file = open(fname,'w')
    kml_file.write(kml_text)
    kml_file.close()
    print "Created ",fname
Beispiel #24
0
def run_sw(hl=3.,ul=0.,hr=1.,ur=0.):
	os.system("make .exe")
	import setrun
	rundata = setrun.setrun()  # initialize most run-time variables for clawpack
	outdir = '_output'

	# IC for shallow water code
	rundata.probdata.hl = hl
	rundata.probdata.ul = ul
	rundata.probdata.hr = hr
	rundata.probdata.ur = ur
	rundata.write()

	os.system("make output > output.txt")
	os.system("make plots >> output.txt")
Beispiel #25
0
    def __init__(self, storm, storm_number):
        r"""
        Initialize Habanero storm surge job

        See :class:`StormJob` for full documentation
        """

        super(StormJob, self).__init__()

        self.storm_number = storm_number
        self.storm = storm

        # Habanero queue settings
        self.omp_num_threads = 24
        self.time = "1:00:00"
        self.queue = ""

        # General job info
        self.type = "surge"
        self.name = "global_1"
        self.prefix = "storm_%s" % self.storm_number
        self.executable = "xgeoclaw"

        # Modify run data
        import setrun
        self.rundata = setrun.setrun()

        # Modify output times
        self.rundata.clawdata.output_style = 2
        recurrence = 6.0
        tfinal = (storm.t[-1] - storm.t[0]).total_seconds()
        N = int(tfinal / (recurrence * 60**2))
        self.rundata.clawdata.output_times = [
            t for t in numpy.arange(0.0, N * recurrence * 60**2, recurrence *
                                    60**2)
        ]
        self.rundata.clawdata.output_times.append(tfinal)

        # Modify storm data
        surge_data = self.rundata.surge_data
        base_path = os.path.expandvars(
            os.path.join("$DATA_PATH", "storms", "global", "storms"))
        surge_data.storm_file = os.path.join(
            base_path, 'storm_%s.storm' % (str(i).zfill(5)))
        self.storm.time_offset = storm.t[0]

        print("Writing out GeoClaw storms...")
        self.storm.write(self.rundata.surge_data.storm_file)
    def __init__(self, test = "A"):
        super(BenchmarkBaseTest,self).__init__()
        
        import setrun
        self.run_data = setrun.setrun()

        self.name = "TestOutput"
        self.test = test
       
        if test == "A":
            self.run_data.clawdata.nout = 22
        elif test == "C":
            self.run_data.clawdata.nout = 28

    # Convert angle to degrees for the label
        self.prefix = "Case%s" % test
Beispiel #27
0
    def __init__(self, storm, storm_number):
        r"""
        Initialize Habanero storm surge job

        See :class:`StormJob` for full documentation
        """

        super(StormJob, self).__init__()

        self.storm_number = storm_number
        self.storm = storm

        # Habanero queue settings
        self.omp_num_threads = 24
        self.time = "1:00:00"
        self.queue = ""

        # General job info
        self.type = "surge"
        self.name = "global_1"
        self.prefix = "storm_%s" % self.storm_number
        self.executable = "xgeoclaw"

        # Modify run data
        import setrun
        self.rundata = setrun.setrun()

        # Modify output times
        self.rundata.clawdata.output_style = 2
        recurrence = 6.0
        tfinal = (storm.t[-1] - storm.t[0]).total_seconds()
        N = int(tfinal / (recurrence * 60**2))
        self.rundata.clawdata.output_times = [t for t in
                 numpy.arange(0.0, N * recurrence * 60**2, recurrence * 60**2)]
        self.rundata.clawdata.output_times.append(tfinal)

        # Modify storm data
        surge_data = self.rundata.surge_data
        base_path = os.path.expandvars(os.path.join("$DATA_PATH", "storms",
                                                    "global", "storms"))
        surge_data.storm_file = os.path.join(base_path,
                                             'storm_%s.storm'
                                             % (str(i).zfill(5)))
        self.storm.time_offset = storm.t[0]

        print("Writing out GeoClaw storms...")
        self.storm.write(self.rundata.surge_data.storm_file)
Beispiel #28
0
def make_input_data_kmls(rundata=None, combined=False):
    """
    Produce kml files for the computational domain, all gauges and regions 
    specified, and all topo and dtopo files specified in rundata.
    This can be used, e.g. by adding the lines 

        from clawpack.geoclaw import kmltools
        kmltools.make_input_data_kmls(rundata)

    to the end of a `setrun.py` file so that `make data` will generate all
    kml files in addition to the `*.data` files.
    
    Or set *rundata==None*, in which case it will try to generate rundata
    based on executing function *setrun*
    from the `setrun.py` file in the current directory.
    """

    import os
    from clawpack.geoclaw import topotools, dtopotools

    if rundata is None:
        try:
            import setrun
            reload(setrun)
            rundata = setrun.setrun()
        except:
            raise IOError("*** cannot execute setrun file")

    regions2kml(rundata, combined=combined)
    gauges2kml(rundata)
    fgmax2kml(rundata)

    topofiles = rundata.topo_data.topofiles
    for f in topofiles:
        topo_file_name = f[-1]
        topo_type = f[0]
        topo2kml(topo_file_name, topo_type)

    dtopofiles = rundata.dtopo_data.dtopofiles
    for f in dtopofiles:
        dtopo_file_name = f[-1]
        dtopo_type = f[0]
        dtopo2kml(dtopo_file_name, dtopo_type)
Beispiel #29
0
    def __init__(self, storm_num, base_path='./', storms_path='./'):

        super(StormJob, self).__init__()

        self.type = ""
        self.name = ""
        self.prefix = str(storm_num).zfill(5)
        self.storm_num = storm_num
        self.executable = "xgeoclaw"

        # Create base data object
        import setrun
        self.rundata = setrun.setrun()

        # Storm specific data
        self.storm_file_path = os.path.abspath(
            os.path.join(storms_path, "%s.storm" % storm_num))

        # Set storm file
        self.rundata.storm_data.storm_file = self.storm_file_path
Beispiel #30
0
    def __init__(self,
                 run_number=1,
                 wave_tolerance=1.0,
                 deep_depth=300.0,
                 speed_tolerance=False):

        super(SweepJob, self).__init__(time=24 * 60, memory=15000)

        self.omp_num_threads = 16

        self.run_number = run_number
        self.type = 'sweep'
        if speed_tolerance:
            self.name = 'wave_deep_speed_l5'
        else:
            self.name = 'wave_deep_no_speed_l5'
        self.prefix = 'run_%s_wave_%s_deep_%s' % (self.run_number,
                                                  wave_tolerance, deep_depth)
        self.executable = 'xgeoclaw'

        self.group = 'yetiapam'

        import setrun
        self.rundata = setrun.setrun()

        # incorporate storm parameters
        self.rundata.add_data(surge.SurgeData(), 'stormdata')
        setrun.set_storm(self.rundata)
        self.rundata.add_data(surge.FrictionData(), 'frictiondata')
        setrun.set_friction(self.rundata)

        ### modify setrun parameters here ###
        refine_data = self.rundata.refinement_data
        refine_data.wave_tolerance = wave_tolerance
        refine_data.deep_depth = deep_depth
        if not speed_tolerance:
            refine_data.speed_tolerance = [999999
                                           ]  #big number so it never triggers

        amrdata = self.rundata.amrdata
        amrdata.amr_levels_max = 5
Beispiel #31
0
    def __init__(self,
                 angle=0.0,
                 bathy_angle=0.0,
                 location=[-0.1, 0.0],
                 bathy_location=0.15):

        super(PlaneWaveTest, self).__init__()

        self.executable = 'xgeoclaw'
        self.type = "multilayer"
        self.name = "planewave"

        # Convert angle to degrees for the label
        self.prefix = "ml_2d_ia%s_ba%s" % (int(
            angle * 180.0 / numpy.pi), int(bathy_angle * 180.0 / numpy.pi))

        # Data objects
        self.rundata = setrun.setrun()

        self.rundata.qinit_data.angle = angle
        self.rundata.qinit_data.init_location = location

        self.bathy_location = bathy_location
        self.bathy_angle = bathy_angle

        # Add gauges down perpendicular
        self.rundata.gaugedata.gauges = []
        gauge_locations = [-0.1, 0.0, 0.1, 0.2, 0.3]
        for (i, x_c) in enumerate(gauge_locations):
            # y0 = (self.run_data.clawdata.yupper - self.run_data.clawdata.ylower) / 2.0
            # x_p,y_p = transform_c2p(x_c,0.0,location[0],location[1],angle)
            x_p = x_c * numpy.cos(angle)
            y_p = x_c * numpy.sin(angle)
            # print "+=====+"
            # print x_c,0.0
            # print x_p,y_p
            if (self.rundata.clawdata.lower[0] < x_p <
                    self.rundata.clawdata.upper[0]
                    and self.rundata.clawdata.lower[1] < y_p <
                    self.rundata.clawdata.upper[1]):
                self.rundata.gaugedata.gauges.append([i, x_p, y_p, 0.0, 1e10])
    def __init__(self, wind_model, amr_level):
        r"""
        Initialize a StormJob object.

        See :class:`StormJob` for full documentation

        """

        super(StormJob, self).__init__()

        self.type = "storm-surge"

        self.name = "ike-amr%s" % str(amr_level)
        self.prefix = "%s" % (wind_model)
        self.executable = 'xgeoclaw'

        # Data objects
        import setrun
        self.rundata = setrun.setrun()

        self.rundata.surge_data.storm_specification_type = wind_model
        self.rundata.amrdata.amr_levels_max = amr_level
Beispiel #33
0
    def __init__(self, ensemble, storm_num, base_path='./', storms_path='./'):

        super(StormJob, self).__init__()

        self.type = ""
        self.name = ""
        self.prefix = str(storm_num).zfill(5)
        self.storm_num = storm_num
        self.executable = "xgeoclaw"

        # Create base data object
        import setrun
        self.rundata = setrun.setrun()

        # Storm specific data
        self.ensemble = ensemble
        self.storm_file_path = os.path.join(storms_path
                               os.path.abspath("./%s.storm" % storm_num))

        # Set storm file
        self.rundata.storm_data.storm_type = 1
        self.rundata.storm_data.storm_file = self.storm_file_path
Beispiel #34
0
    def __init__(self, eigen_method=1):

        super(BubbleTest, self).__init__()

        self.type = "multilayer"
        self.name = "bubble"
        self.prefix = "ml_e%s" % eigen_method

        # Data objects
        self.rundata = setrun.setrun()

        self.rundata.clawdata.lower = [0.0, 0.0]
        self.rundata.clawdata.upper = [1.0, 1.0]
        self.rundata.clawdata.num_cells = [100, 100]
        self.rundata.multilayer_data.eigen_method = eigen_method
        self.rundata.multilayer_data.eta = [0.0, -0.5]

        self.rundata.qinit_data.qinit_type = 7
        self.rundata.qinit_data.init_location = [-0.25,0.0]
        self.rundata.qinit_data.wave_family = 0
        self.rundata.qinit_data.epsilon = 0.4
        self.rundata.qinit_data.sigma = 0.08

        self.bathy_location = 0.8
Beispiel #35
0
    def __init__(self, eigen_method=1):

        super(BubbleTest, self).__init__()

        self.type = "multilayer"
        self.name = "bubble"
        self.prefix = "ml_e%s" % eigen_method

        # Data objects
        self.rundata = setrun.setrun()

        self.rundata.clawdata.lower = [0.0, 0.0]
        self.rundata.clawdata.upper = [1.0, 1.0]
        self.rundata.clawdata.num_cells = [100, 100]
        self.rundata.multilayer_data.eigen_method = eigen_method
        self.rundata.multilayer_data.eta = [0.0, -0.5]

        self.rundata.qinit_data.qinit_type = 7
        self.rundata.qinit_data.init_location = [-0.25, 0.0]
        self.rundata.qinit_data.wave_family = 0
        self.rundata.qinit_data.epsilon = 0.4
        self.rundata.qinit_data.sigma = 0.08

        self.bathy_location = 0.8
Beispiel #36
0
    def __init__(self, angle=0.0, bathy_angle=0.0, location=[-0.1, 0.0], 
                       bathy_location=0.15):

        super(PlaneWaveTest, self).__init__()

        self.executable = 'xgeoclaw'
        self.type = "multilayer"
        self.name = "planewave"

        # Convert angle to degrees for the label
        self.prefix = "ml_2d_ia%s_ba%s" % (int(angle * 180.0 / numpy.pi),
            int(bathy_angle * 180.0 / numpy.pi))

        # Data objects
        self.rundata = setrun.setrun()

        self.rundata.qinit_data.angle = angle
        self.rundata.qinit_data.init_location = location

        self.bathy_location = bathy_location
        self.bathy_angle = bathy_angle

        # Add gauges down perpendicular
        self.rundata.gaugedata.gauges = []
        gauge_locations = [-0.1,0.0,0.1,0.2,0.3]
        for (i,x_c) in enumerate(gauge_locations):
            # y0 = (self.run_data.clawdata.yupper - self.run_data.clawdata.ylower) / 2.0
            # x_p,y_p = transform_c2p(x_c,0.0,location[0],location[1],angle)
            x_p = x_c * numpy.cos(angle)
            y_p = x_c * numpy.sin(angle)
            # print "+=====+"
            # print x_c,0.0
            # print x_p,y_p
            if (self.rundata.clawdata.lower[0] < x_p < self.rundata.clawdata.upper[0] and
                    self.rundata.clawdata.lower[1] < y_p < self.rundata.clawdata.upper[1]):
                self.rundata.gaugedata.gauges.append([i, x_p, y_p, 0.0, 1e10])
Beispiel #37
0
    def __init__(self, deformation_file, topo_type=None):

        super(FaultJob, self).__init__()

        self.type = "compsyn"
        self.name = "guerrero_gap"
        self.executable = 'xgeoclaw'

        # Given an xyzt file, use this to run simulation
        self.deformation_file = os.path.abspath(deformation_file)
        self.prefix = os.path.basename(deformation_file).split('.')[0]

        # Data objects
        import setrun
        self.rundata = setrun.setrun()

        # Add deformation file
        self.rundata.dtopo_data.dtopofiles = []
        if topo_type is None:
            # Try to look at suffix for type
            extension = os.path.splitext(deformation_file)[1][1:]
            if extension[:2] == "tt":
                topo_type = int(extension[2])
            elif extension == 'xyz':
                topo_type = 1
            else:
                # Default to 3
                topo_type = 3
        self.rundata.dtopo_data.dtopofiles.append(
            [topo_type, 3, 5, self.deformation_file])
        # Add earthquake to regions list, force refinement for 1 minute
        regions = self.rundata.regiondata.regions
        regions.append([
            7, 7, 0.0, 60e0, -99.463937141374046, -98.485815563597853,
            16.622495995962375, 17.490586994378546
        ])
Beispiel #38
0
    def __init__(self, deformation_file, topo_type=None):

        super(FaultJob, self).__init__()

        self.type = "compsyn"
        self.name = "guerrero_gap"
        self.executable = 'xgeoclaw'

        # Given an xyzt file, use this to run simulation
        self.deformation_file = os.path.abspath(deformation_file)
        self.prefix = os.path.basename(deformation_file).split('.')[0]

        # Data objects
        import setrun
        self.rundata = setrun.setrun()

        # Add deformation file
        self.rundata.dtopo_data.dtopofiles = []
        if topo_type is None:
            # Try to look at suffix for type
            extension = os.path.splitext(deformation_file)[1][1:]
            if extension[:2] == "tt":
                topo_type = int(extension[2])
            elif extension == 'xyz':
                topo_type = 1
            else:
                # Default to 3
                topo_type = 3
        self.rundata.dtopo_data.dtopofiles.append(
                                          [topo_type,3,5,self.deformation_file])
        # Add earthquake to regions list, force refinement for 1 minute
        regions = self.rundata.regiondata.regions
        regions.append([7, 7, 0.0, 60e0, -99.463937141374046, 
                                         -98.485815563597853, 
                                          16.622495995962375, 
                                          17.490586994378546 ])
Beispiel #39
0
def regions2kml(rundata=None,
                fname='regions.kml',
                verbose=True,
                combined=True):
    """
    Create a KML box for each AMR region specified for a GeoClaw run.

    :Inputs:

      - *rundata* - an object of class *ClawRunData* or None

        If *rundata==None*, try to create based on executing function *setrun*
        from the `setrun.py` file in the current directory.

      - *fname* (str) - resulting kml file.

      - *verbose* (bool) - If *True*, print out info about each region found

      - *combined* (bool) - If *True*, combine into single kml file with
        name given by *fname*.  This is the default. 
        If False, *fname* is ignored and individual files are created for
        each region with names are Domain.kml, Region00.kml, etc.
        These will show up separately in GoogleEarth so they can be turned
        on or off individually.

    First create a box for the entire domain (in red) and then a box
    for each region (in white).

    :Example:

        >>> from clawpack.geoclaw import kmltools
        >>> kmltools.regions2kml()

    is equivalent to:

        >>> from clawpack.geoclaw import kmltools
        >>> from setrun import setrun
        >>> rundata = setrun()
        >>> kmltools.regions2kml(rundata)

    By default this creates a file named *regions.kml* that can be opened in
    Google Earth.

    """

    from numpy import cos, pi, floor

    if rundata is None:
        try:
            import setrun
            reload(setrun)
            rundata = setrun.setrun()
        except:
            raise IOError("*** cannot execute setrun file")

    clawdata = rundata.clawdata
    x1, y1 = clawdata.lower[0:]
    x2, y2 = clawdata.upper[0:]
    description = "  x1 = %g, x2 = %g\n" % (x1,x2) \
            + "  y1 = %g, y2 = %g\n" % (y1,y2)

    mx, my = clawdata.num_cells[0:]
    dx = (x2 - x1) / float(mx)
    dx_meters = dx * 111e3 * cos(pi * 0.5 * (y1 + y2) / 180.)
    dy = (y2 - y1) / float(my)
    dy_meters = dy * 111e3
    if verbose:
        print("Domain:   %10.6f  %10.6f  %10.6f  %10.6f" % (x1, x2, y1, y2))
    dx_deg, dx_min, dx_sec = deg2dms(dx)
    dy_deg, dy_min, dy_sec = deg2dms(dy)
    #print "Level 1 resolution:  dx = %g deg, %g min, %g sec = %g meters" \
    #   % (dx_deg,dx_min,dx_sec,dx_meters)
    levtext = "Level 1 resolution:  dy = %g deg, %g min, %g sec = %g meters\n" \
        % (dy_deg,dy_min,dy_sec,dy_meters)
    if verbose:
        print(levtext)
    description = description + levtext

    amr_levels_max = rundata.amrdata.amr_levels_max
    refinement_ratios_y = rundata.amrdata.refinement_ratios_y
    num_ref_ratios = len(refinement_ratios_y)
    if amr_levels_max > num_ref_ratios + 1:
        raise IOError("*** Too few refinement ratios specified for " \
            + "amr_levels_max = %i" % amr_levels_max)
    dy_levels = (num_ref_ratios + 1) * [dy]
    for k, r in enumerate(refinement_ratios_y):
        level = k + 2
        dy = dy_levels[k] / r
        dy_levels[k + 1] = dy
        dy_meters = dy * 111e3
        dy_deg, dy_min, dy_sec = deg2dms(dy)
        levtext = "Level %s resolution:  dy = %g deg, %g min, %g sec = %g meters  (refined by %i)\n" \
                % (level,dy_deg,dy_min,dy_sec,dy_meters,r)
        if verbose:
            print(levtext)
        description = description + levtext

    if verbose:
        print("Allowing maximum of %i levels" % amr_levels_max)

    elev = 0.
    if not combined:
        fname = 'Domain.kml'

    kml_text = kml_header(fname)

    mapping = {}
    mapping['x1'] = x1
    mapping['x2'] = x2
    mapping['y1'] = y1
    mapping['y2'] = y2
    mapping['elev'] = elev
    mapping['name'] = 'Computational Domain'
    mapping['desc'] = description
    mapping['color'] = "0000FF"  # red
    mapping['width'] = 2

    region_text = kml_region(mapping)
    kml_text = kml_text + region_text

    if not combined:
        kml_text = kml_text + kml_footer()
        kml_file = open(fname, 'w')
        kml_file.write(kml_text)
        kml_file.close()
        if verbose:
            print("Created ", fname)

    regions = rundata.regiondata.regions
    if len(regions) == 0 and verbose:
        print("No regions found in setrun.py")

    for rnum, region in enumerate(regions):
        if not combined:
            fname = 'Region_%s.kml' % str(rnum).zfill(2)
            kml_text = kml_header(fname)

        minlevel, maxlevel = region[0:2]
        t1, t2 = region[2:4]
        x1, x2, y1, y2 = region[4:]

        if verbose:
            print("Region %i: %10.6f  %10.6f  %10.6f  %10.6f" \
                    % (rnum,x1,x2,y1,y2))
            print("           minlevel = %i,  maxlevel = %i" \
                    % (minlevel,maxlevel) \
                    + "  t1 = %10.1f,  t2 = %10.1f" % (t1,t2))
        mapping = {}
        mapping['minlevel'] = minlevel
        mapping['maxlevel'] = maxlevel
        mapping['t1'] = t1
        mapping['t2'] = t2
        mapping['x1'] = x1
        mapping['x2'] = x2
        mapping['y1'] = y1
        mapping['y2'] = y2
        mapping['elev'] = elev
        mapping['name'] = 'Region %i' % rnum
        description = "minlevel = %i, maxlevel = %i\n" % (minlevel,maxlevel) \
            + "  t1 = %g, t2 = %g\n" % (t1,t2) \
            + "  x1 = %g, x2 = %g\n" % (x1,x2) \
            + "  y1 = %g, y2 = %g\n\n" % (y1,y2)
        if len(dy_levels) >= minlevel:
            dy = dy_levels[minlevel - 1]
            dy_deg, dy_min, dy_sec = deg2dms(dy)
            dy_meters = dy * 111e3
            levtext = "Level %s resolution:  \ndy = %g deg, %g min, %g sec \n= %g meters\n" \
                    % (minlevel,dy_deg,dy_min,dy_sec,dy_meters)
            description = description + levtext
        if (maxlevel > minlevel) and (len(dy_levels) >= maxlevel):
            dy = dy_levels[maxlevel - 1]
            dy_deg, dy_min, dy_sec = deg2dms(dy)
            dy_meters = dy * 111e3
            levtext = "\nLevel %s resolution:  \ndy = %g deg, %g min, %g sec \n= %g meters\n" \
                    % (maxlevel,dy_deg,dy_min,dy_sec,dy_meters)
            description = description + levtext
        mapping['desc'] = description
        mapping['color'] = "FFFFFF"  # white
        mapping['width'] = 3

        region_text = kml_region(mapping)
        kml_text = kml_text + region_text
        if not combined:
            kml_text = kml_text + kml_footer()
            kml_file = open(fname, 'w')
            kml_file.write(kml_text)
            kml_file.close()
            if verbose:
                print("Created ", fname)

    if combined:
        kml_text = kml_text + kml_footer()
        kml_file = open(fname, 'w')
        kml_file.write(kml_text)
        kml_file.close()
        if verbose:
            print("Created ", fname)
Beispiel #40
0
#! /usr/bin/python

"""
Run several tests with different parameters, in this case different
values of d.
"""

from setrun import setrun
from setplot import setplot
from pyclaw.runclaw import runclaw
from pyclaw.plotters.plotclaw import plotclaw

for n in [1,2,4]:
    for d in [0.061, 0.080, 0.100, 0.120, 0.140, 0.149, 0.189]:
        rundata = setrun(d_param=d)
        mx = 72*n
        my = 18*n
        rundata.clawdata.mx = mx
        rundata.clawdata.my = my
        rundata.write()

        runclaw(xclawcmd = "xgeoclaw", outdir="_output_%s_my%s" % (d,my))

        setplot.d = d
        setplot.my = my
        plotclaw(outdir="_output_%s_my%s" % (d,my), \
                 plotdir="_plots_%s_my%s" % (d,my),\
                 setplot=setplot)


Beispiel #41
0
    def __init__(self, slips):
        r"""
        Initialize a FaultJob object.
        
        See :class:`FaultJob` for full documentation
        
        """

        super(FaultJob, self).__init__()

        # Create fault
        # Based on UCSB reconstruction and assumption of single subfault
        # Lengths are based on num_fault_segments * dx * m/km in each direction
        #
        # Top edge    Bottom edge
        #   a ----------- b          ^
        #   |             |          |         ^
        #   |             |          |         |
        #   |             |          |         | along-strike direction
        #   |             |          |         |
        #   0------1------2          | length  |
        #   |             |          |
        #   |             |          |
        #   |             |          |
        #   |             |          |
        #   d ----------- c          v
        #   <------------->
        #       width
        # <-- up dip direction
        #
        #  Given
        #      Long            Lat             Depth
        #  a = 144.56380       39.66720        7.50520
        #  b = 140.76530       36.15960       41.96770
        #  c = 142.43800       40.21080       41.96770
        #  d = 142.89110       35.61610        7.50520
        #  Computed
        #      Long            Lat             Depth
        #  0 = 143.72745       37.64165        7.50520
        # Comparison Fault System
        UCSB_fault = dtopotools.UCSBFault('./UCSB_model3_subfault.txt')

        # Use data from the reconstruced UCSB fault to setup our fault system
        # Calculate average quantities across all subfaults
        ave_rake = 0.0
        ave_strike = 0.0
        ave_slip = 0.0
        for subfault in UCSB_fault.subfaults:
            ave_rake = subfault.rake
            ave_strike = subfault.strike
            ave_slip = subfault.slip

        ave_rake /= len(UCSB_fault.subfaults)
        ave_strike /= len(UCSB_fault.subfaults)
        ave_slip /= len(UCSB_fault.subfaults)

        # Base subfault
        self.base_subfault = dtopotools.SubFault()
        self.base_subfault.strike = 198.0
        self.base_subfault.length = 19 * 25.0 * 1000.0
        self.base_subfault.width = 10 * 20.0 * 1000.0
        self.base_subfault.depth = 7.50520 * 1000.0
        self.base_subfault.slip = slip
        self.base_subfault.rake = 90.0
        self.base_subfault.dip = 10.0
        self.base_subfault.latitude = 37.64165
        self.base_subfault.longitude = 143.72745
        self.base_subfault.coordinate_specification = "top center"

        # Create base subdivided fault
        self.fault = dtopotools.SubdividedPlaneFault(self.base_subfault,
                                                     nstrike=3,
                                                     ndip=2)
        for (k, subfault) in enumerate(self.fault.subfaults):
            subfault.slip = slips[k]

        self.type = "tohoku"
        self.name = "okada-fault-PC-analysis"
        self.prefix = "fault_s%s" % (self.base_subfault.slip)
        self.executable = 'xgeoclaw'

        # Data objects
        import setrun
        self.rundata = setrun.setrun()

        # No variable friction for the time being
        self.rundata.friction_data.variable_friction = False

        # Replace dtopo file with our own
        self.dtopo_path = 'fault_s%s.tt3' % self.base_subfault.slip
        self.rundata.dtopo_data.dtopofiles = [[3, 4, 4, self.dtopo_path]]
    def __init__(self, prefix, storm_directory, storm, wind_model, amr_level,
                 storm_ensemble_type, region):
        r"""
        Initialize a MumbaiStormJob object.

        See :class:`MumbaiStormJob` for full documentation

        """

        super(MumbaiStormJob, self).__init__()

        self.type = "storm-surge"
        self.storm_ensemble_type = storm_ensemble_type
        self.region = region

        self.storm_directory = storm_directory
        self.storm = storm

        self.name = "%s-amr%s" % (wind_model, amr_level)
        self.prefix = str(prefix).zfill(4)
        self.executable = 'xgeoclaw'

        # Data objects
        import setrun
        self.rundata = setrun.setrun()

        # Set rundata friction, surge, and clawdata variables
        self.rundata = setrun.set_friction(self.rundata)

        # Set surge data
        self.rundata = setrun.set_storm(self.rundata)
        self.rundata.surge_data.storm_specification_type = wind_model

        # Determine time offse
        x_domain = numpy.abs(
            [self.rundata.clawdata.lower[0], self.rundata.clawdata.upper[0]])
        y_domain = numpy.abs(
            [self.rundata.clawdata.lower[1], self.rundata.clawdata.upper[1]])
        x = storm.eye_location[:, 0]
        y = storm.eye_location[:, 1]
        for b in range(0, len(x)):
            if numpy.abs(x[b]) >= (x_domain[0]) and numpy.abs(
                    x[b]) <= (x_domain[1]):
                if numpy.abs(y[b]) >= (y_domain[0]) and numpy.abs(
                        y[b]) <= (y_domain[1]):
                    #storm.time_offset = (storm.t[b],b)
                    self.storm.time_offset = self.storm.t[b]
                    break

        # Set initial time
        #delta_t0 = self.storm.t[0] - self.storm.time_offset
        #self.rundata.clawdata.t0 = days2seconds(delta_t0.days)/2
        self.rundata.clawdata.t0 = days2seconds(0.0)

        # clawdata.tfinal value is the entire length of the track in days
        tf = self.storm.t[-1] - self.storm.t[0]
        self.rundata.clawdata.tfinal = days2seconds(tf.days) + tf.seconds

        # Set refinement
        self.rundata.amrdata.amr_levels_max = amr_level

        # == setregions.data values ==
        # Mumbai Region
        self.rundata.regiondata.regions.append([
            2, 5, self.rundata.clawdata.t0, self.rundata.clawdata.tfinal, 70,
            75, 17, 22
        ])
        # Mumbai
        self.rundata.regiondata.regions.append([
            4, 7,
            days2seconds(1.0), self.rundata.clawdata.tfinal, 72.6, 73, 18.80,
            19.15
        ])

        # Set Gauge Data
        # for gauges append lines of the form  [gaugeno, x, y, t1, t2]
        self.rundata.gaugedata.gauges = []
        self.rundata.gaugedata.gauges.append([
            1, 72.811790, 18.936508, self.rundata.clawdata.t0,
            self.rundata.clawdata.tfinal
        ])
        self.rundata.gaugedata.gauges.append([
            2, 72.972316, 18.997762, self.rundata.clawdata.t0,
            self.rundata.clawdata.tfinal
        ])
        self.rundata.gaugedata.gauges.append([
            3, 72.819311, 18.818044, self.rundata.clawdata.t0,
            self.rundata.clawdata.tfinal
        ])
        self.rundata.gaugedata.gauges.append([
            4, 72.50, 18.50, self.rundata.clawdata.t0,
            self.rundata.clawdata.tfinal
        ])

        # Include auxillary gauge data
        self.rundata.gaugedata.aux_out_fields = [4, 5, 6]

        # Write storm data objects
        storm_file = "%s_%s.storm" % (self.region, self.prefix)
        self.rundata.surge_data.storm_file = os.path.join(
            self.storm_directory, storm_file)

        self.storm.write(self.rundata.surge_data.storm_file,
                         file_format="geoclaw")
#for mx in [ 360*128, 360*8, 360*16, 360*32, 360*64]:
#for mx in [ 360*64, 360*4, 360*8,  360*16, 360*32]:
#for mx in [ 1500*2**5, 1500*2, 1500*2**2, 1500*2**3, 1500*2**4]:
#for mx in [ 1500*2**4, 1500, 1500*2, 1500*2**2,1500*2**3]:
#for mx in [20, 10]:

    if i == 0:
	mx_exact = mx
    xlower = 0.000000e+00
    xupper = 1.000000e+00
    mframe = 10 
    dx = (xupper - xlower)/mx


    #Set setrun clawdata (some maybe unnecessary, will see)
    rundata=setrun.setrun('classic')

    rundata.clawdata.num_cells[0] = mx
    rundata.clawdata.num_output_times = mframe	# output_times=1 won't work for high grid resolution
    rundata.clawdata.tfinal = 0.100000e+00
    rundata.clawdata.lower[0] = xlower
    rundata.clawdata.upper[0] = xupper 
    rundata.clawdata.order = 1
    rundata.clawdata.bc_lower[0] = 'periodic'#'user'   # at xlower
    rundata.clawdata.bc_upper[0] = 'periodic'#'extrap'   # at xupper
    rundata.write()
    runclaw(xclawcmd='xclaw',outdir=outdir)	# xclaw.exe file produced after make .exe 

    #Get the material parameters
    aux = np.loadtxt(outdir+'/fort.a0000',skiprows=5)	# don't delate skiprows or set it equal 6 
from __future__ import print_function

import os, sys

from clawpack.geoclaw_1d import geoplot
from imp import reload

import setrun
rundata=setrun.setrun()

import mapc2p
reload(mapc2p)  # in case num_cells changed
from mapc2p import mapc2p


import numpy
from pylab import find

try:
    fname = '_output/fort.hmax'
    d = numpy.loadtxt(fname)
    etamax = numpy.where(d[:,1]>1e-6, d[:,2], numpy.nan)
    xmax = d[:,0]
    jmax = find(d[:,1]>0).max()
    print("run-in = %8.2f,  run-up = %8.2f" % (d[jmax,0],d[jmax,2]))
    print('Loaded hmax from ',fname)
except:
    xmax = None
    print("Failed to load fort.hmax")
Beispiel #45
0
    def __init__(self, run_number, storm_directory, storm_object, wind_model,
                 amr_level, storm_ensemble_type, region, gauges, regions):
        r"""
        Initialize a StormJob object.

        See :class:`StormJob` for full documentation

        """

        super(StormJob, self).__init__()

        self.type = "storm-surge"
        self.storm_ensemble_type = storm_ensemble_type
        self.region = region

        self.storm_directory = storm_directory
        self.storm_object = storm_object

        self.name = "%s-amr%s" % (wind_model, amr_level)
        self.prefix = str(run_number).zfill(4)
        self.executable = 'xgeoclaw'

        # Data objects
        import setrun
        self.rundata = setrun.setrun()

        # Set rundata friction, surge, and clawdata variables
        # self.rundata = setrun.set_friction(self.rundata)

        # Set rundata friction, surge, and clawdata variables
        self.rundata = setrun.setgeo(self.rundata)

        # Set surge data
        # self.rundata = setrun.set_storm(self.rundata)
        self.rundata.surge_data.storm_specification_type = wind_model

        self.rundata.clawdata.t0 = days2seconds(0.0)

        # clawdata.tfinal value is the entire length of the track in days
        tf = self.storm_object.t[-1] - self.storm_object.t[0]
        self.rundata.clawdata.tfinal = days2seconds(tf.days) + tf.seconds

        # Set refinement
        self.rundata.amrdata.amr_levels_max = amr_level

        # Set storm wind model
        self.rundata.surge_data.storm_specification_type = wind_model

        # Include auxillary gauge data
        self.rundata.gaugedata.aux_out_fields = [4, 5, 6]

        # Write storm data objects
        storm_file = "%s_%s.storm" % (self.region, self.prefix)
        self.rundata.surge_data.storm_file = os.path.join(
            self.storm_directory, storm_file)

        self.storm_object.write(self.rundata.surge_data.storm_file,
                                file_format="geoclaw")

        # Set gauges
        if gauges is not None:
            for i in range(0, len(gauges)):
                print(i + 1, gauges[i][0], gauges[i][1])
                self.rundata.gaugedata.gauges.append([
                    i + 1, gauges[i][0], gauges[i][1],
                    self.rundata.clawdata.t0, self.rundata.clawdata.tfinal
                ])
            print(self.rundata.gaugedata.gauges)

        # Set region data
        if regions is not None:
            for i in range(0, len(regions)):
                self.rundata.regiondata.regions.append([
                    regions[i][0], regions[i][1], self.rundata.clawdata.t0,
                    self.rundata.clawdata.tfinal, regions[i][2], regions[i][3],
                    regions[i][4], regions[i][5]
                ])
Beispiel #46
0
def run_code_or_restart():

    import time
    tm = time.localtime()
    year = str(tm[0]).zfill(4)
    month = str(tm[1]).zfill(2)
    day = str(tm[2]).zfill(2)
    hour = str(tm[3]).zfill(2)
    minute = str(tm[4]).zfill(2)
    second = str(tm[5]).zfill(2)
    timestamp = '%s-%s-%s-%s%s%s'  % (year,month,day,hour,minute,second)

    finished, latest, t_latest = examine_outdir(outdir)

    if finished:
        print("Code has finished running, remove %s to run again" % outdir)
        return

    restart = (latest is not None)

    fname_output = 'run_output.txt'
    fname_errors = 'run_errors.txt'

    if restart:
        print("Will attempt to restart using checkpoint file %s at t = %s" \
                % (latest, t_latest))
        print("Appending output stream to %s" % fname_output)
        access = 'a'
    else:
        print("Will run code -- no restart")
        print("Writing output stream to %s" % fname_output)
        access = 'w'

    fout = open(fname_output, access)
    ferr = open(fname_errors, access)

    if restart:
        fout.flush()
        fout.write("\n=========== RESTART =============\n" + \
                "Local time: %s\n" % timestamp + \
                "Will attempt to restart using checkpoint file %s at t = %s\n" \
                % (latest, t_latest))
        fout.flush()
        make_args = ['make','output','RESTART=True']
    else:
        make_args = ['make','output']

    #if restart:
    #    No longer need to do this since new restart now adds to gauge*.txt files
    #    fortgauge = os.path.join(outdir,'fort.gauge')
    #    fortgauge2 = os.path.join(outdir,'fort.gauge_%s' % timestamp)
    #    os.system("mv %s %s" % (fortgauge,fortgauge2))
    #    fout.write("Moving %s to %s \n" % (fortgauge,fortgauge2))
    #    fout.flush()

    rundata = setrun('amrclaw')
    rundata.clawdata.restart = restart
    rundata.clawdata.restart_file = 'fort.chk' + str(latest)
    if restart:
        rundata.clawdata.output_t0 = False  # to avoid plotting at restart times
    rundata.write()
    
    job = subprocess.Popen(make_args, stdout=fout,stderr=ferr,env=env)
    return_code = job.wait()
    
    if return_code == 0:
        print("Successful run\n")
    else:
        print("Problem running code\n")
    print("See %s and %s" % (fname_output,fname_errors))
    
    fout.close()
    ferr.close()
Beispiel #47
0
import numpy as np
import matplotlib.pyplot as pl
from pyclaw.plotters.data import ClawPlotData
from sharpclawtest import compute_exact_solution
import setrun
from pyclaw.runclaw import runclaw
reload(setrun)

outdir='./_output'
frame=1
err=[]

#for mx in [200,400,800,1600,3200]:
for mx in [3200,6400]:
    rundata=setrun.setrun('sharpclaw')
    rundata.probdata.ic=9
    rundata.probdata.x0=-4.0
    rundata.probdata.a=4.0  # 1 for narrow pulse, 4 for wide pulse
    rundata.clawdata.mx=mx
    rundata.clawdata.nout=1
    rundata.clawdata.tfinal=8
    rundata.write()
    runclaw(xclawcmd='xsclaw',outdir=outdir)

    #Get the material parameters
    aux = np.loadtxt(outdir+'/fort.aux')
    rho = aux[:,0]; K   = aux[:,1]

    plotdata = ClawPlotData()
    plotdata.outdir=outdir
Beispiel #48
0
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.

    """
    import setrun

    setrundata = setrun.setrun()

    plotdata.clearfigures()  # clear any old figures,axes,items data

    def q_1d_fill(current_data):
        X = current_data.x
        Y = current_data.y
        a2dvar = current_data.var
        a2dvar2 = current_data.var2
        dy = current_data.dy

        #yind = np.where(np.abs(Y[0,:]-1.0)<=dy/2.0)[0]
        #xind = np.where(X[:,0]> -1.e10)[0]

        if (current_data.grid.level == 3):
            yind = np.where(np.abs(Y[0, :] - 1.0) <= dy)[0]
            xind = np.where(X[:, 0] > -1.e10)[0]
        else:
            yind = np.where(Y[0, :] > 1.e10)[0]
            xind = np.where(X[:, 0] > 1.e10)[0]

        x = X[np.ix_(xind, yind)]
        a1dvar = a2dvar[np.ix_(xind, yind)]  #-x*np.sin(31.*np.pi/180.0)
        a1dvar2 = a2dvar2[np.ix_(xind, yind)]  #-x*np.sin(31.*np.pi/180.0)
        #pdb.set_trace() #<-----------------------------

        return x, a1dvar, a1dvar2

    def q_1d(current_data):
        X = current_data.x
        Y = current_data.y
        dy = current_data.dy
        a2dvar = current_data.var

        if (current_data.grid.level == 3):
            yind = np.where(np.abs(Y[0, :] - 1.0) <= dy)[0]
            xind = np.where(X[:, 0] > -1.e10)[0]
        else:
            yind = np.where(Y[0, :] > 1.e10)[0]
            xind = np.where(X[:, 0] > 1.e10)[0]

        x = X[np.ix_(xind, yind)]
        a1dvar = a2dvar[np.ix_(xind, yind)]  #-x*np.sin(31.*np.pi/180.0)

        return x, a1dvar

    def fixup(current_data):
        import pylab

        t = current_data.t
        pylab.title('')
        pylab.xticks([-5.9, -3, 0, 2.9], ('-6.0', '-3.0', '0.0', '3.0'),
                     fontsize=18)
        pylab.yticks([0, 1.0, 1.9], ('0.0', '1.0', '2.0'), fontsize=18)
        pylab.text(-5.5,1.9,'t = %6.2f s'% (t),fontsize=20, style = 'italic', \
            horizontalalignment='left',verticalalignment='top', \
            rotation = 31.0)
        #pdb.set_trace()
        #axx = pylab.gca()
        #scalebars.add_scalebar(axx)
        xbase = np.linspace(-6.0, 0.0, 5000)
        ybase = 0.0 * xbase
        ybase[-1] = 0.65
        pylab.plot(xbase, ybase, 'k-')
        #in front of ramp
        xbase = np.linspace(0.0, 3.0, 5000)
        ybase = 0.0 * xbase
        pylab.plot(xbase, ybase, 'k-')
        pylab.gcf().subplots_adjust(bottom=0.15)
        #pylab.tight_layout()
        return current_data

    def logscale(current_data):
        pplt.gca().set_yscale('log')
        return current_data

    def plot_lagrangian(current_data):

        #lagrangian dots

        if current_data.grid.level < 3:
            return current_data

        t = current_data.t
        #(allgaugedata,xgauges,ygauges,gauge_nums) = cg.getgaugedata('../_output/fort.gauge','../_output/setgauges.data')
        #pdb.set_trace()
        x0Lagrangian = [
            0.0975 - 3.5 + 0.65 * np.sin(theta),
            -2.3 + 0.08 + 0.65 * np.sin(theta),
            -1.1 + 0.0512 + 0.65 * np.sin(theta)
        ]
        xColor = ['c*', 'rp', 'm*']
        vplacement = [0.5, 0.15, 0.5]
        T = np.linspace(0.0, t, 500)
        X = current_data.x
        Y = current_data.y
        dy = current_data.dy
        dx = current_data.dx
        h2d = current_data.q[:, :, 0]
        topo2d = digplot.topo(current_data)

        for x0ind in xrange(len(x0Lagrangian)):
            x0 = x0Lagrangian[x0ind]

            Xoft = cg.Lagrangian_Xoft(allgaugedata, xgauges, gauge_nums, x0, T)
            xnow = Xoft[-1]

            if ((current_data.xupper + 0.5 * dx > xnow) &
                (current_data.xlower - 0.5 * dx <= xnow)):
                yind = np.where(np.abs(Y[0, :] - 1.0) <= dy)[0]
                xind = np.where(X[:, 0] > xnow)[0]
            else:
                yind = np.where(Y[0, :] > 1.e10)[0]
                xind = np.where(X[:, 0] > 1.e10)[0]

            x = X[np.ix_(xind, yind)]
            #pdb.set_trace()
            if (xind.any() & yind.any()):
                h1d = h2d[np.ix_(xind, yind)]  #-x*np.sin(31.*np.pi/180.0)
                topo1d = topo2d[np.ix_(xind, yind)]
                h1d = h1d.flatten()
                topo1d = topo1d.flatten()
                zcoord = topo1d[0] + vplacement[x0ind] * h1d[0]
                if x0ind == 1:
                    zcoord = topo1d[0] + 0.1
                #pdb.set_trace()
                pylab.plot(xnow, zcoord, xColor[x0ind], markersize=14)

        return current_data

    # Figure for surface elevation
    plotfigure = plotdata.new_plotfigure(name='Surface', figno=1)
    plotfigure.kwargs = {'figsize': (9, 2.2), 'frameon': False}
    plotfigure.tight_layout = True
    #    plotfigure.clf_each_frame = False

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.xlimits = [-6.0, 3.0]
    plotaxes.ylimits = [-0.2, 2.0]  #'auto' #[-.1,2.0]
    plotaxes.kwargs = {'frameon': 'False', 'axis': 'off'}
    plotaxes.afteraxes = fixup

    # Set up for item on these axes: (plot tan depth)
    plotitem = plotaxes.new_plotitem(plot_type='1d_fill_between_from_2d_data')
    plotitem.plot_var = digplot.topo
    plotitem.plot_var2 = digplot.eta
    plotitem.map_2d_to_1d = q_1d_fill
    #plotitem.amr_gridlines_show = [1,1,1]

    plotitem.color = 'tan'

    # Set up for item on these axes: (plot blue fill for pressure)
    plotitem = plotaxes.new_plotitem(plot_type='1d_fill_between_from_2d_data')
    plotitem.plot_var = digplot.topo
    plotitem.plot_var2 = digplot.pressure_lithohead_eta
    plotitem.map_2d_to_1d = q_1d_fill
    #plotitem.amr_gridlines_show = [1,1,1]
    plotitem.color = 'blue'

    # Set up for item on these axes: (dark line for topography)
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = digplot.topo
    plotitem.map_2d_to_1d = q_1d
    plotitem.linestyle = '-'
    plotitem.color = 'black'
    plotitem.linewidth = 2.0
    plotitem.show = True

    # Set up for lagrangian points
    #plotitem = plotaxes.new_plotitem(plot_type = '2d_empty')
    #plotitem.aftergrid = plot_lagrangian

    plotitem.show = True

    # figure of surface
    plotfigure = plotdata.new_plotfigure(name='Surface_2', figno=2)
    plotaxes = plotfigure.new_plotaxes()
    plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor')
    plotaxes.xlimits = [-6.0, 6.0]
    plotaxes.ylimits = [-2.0, 4.0]
    plotitem.plot_var = 0  #digplot.pressure_head
    plotitem.pcolor_cmin = 0.0
    plotitem.pcolor_cmax = 1.9
    plotitem.amr_gridlines_show = [1, 1, 0]
    #plotitem.amr_gridedges_show = [1 1 1]

    plotitem.show = True

    # figure of m vs. m_eqn
    plotfigure = plotdata.new_plotfigure(name='meqn', figno=3)
    plotaxes = plotfigure.new_plotaxes()
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = digplot.m_eqn
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'red'
    plotitem.linewidth = 2.0
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = digplot.solid_frac
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'black'
    plotitem.linewidth = 2.0
    plotaxes.ylimits = [0.5, 0.7]
    plotaxes.xlimits = [-6, 70]
    plotitem.show = True

    # figure of rho
    plotfigure = plotdata.new_plotfigure(name='rho', figno=4)
    plotaxes = plotfigure.new_plotaxes()
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = digplot.density
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'red'
    plotitem.linewidth = 2.0
    plotaxes.xlimits = [-6, 70]
    plotitem.show = False

    # figure of Iv
    plotfigure = plotdata.new_plotfigure(name='Iv', figno=5)
    plotaxes = plotfigure.new_plotaxes()
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = digplot.Iv
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'red'
    plotitem.linewidth = 2.0
    plotaxes.xlimits = [-6, 70]
    plotaxes.ylimits = [.00, .0025]
    plotitem.show = True

    # figure of u,v
    plotfigure = plotdata.new_plotfigure(name='uv', figno=6)
    plotaxes = plotfigure.new_plotaxes()
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = digplot.shear_strain
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'blue'
    plotitem.linewidth = 2.0
    plotaxes.xlimits = [-6, 140]
    #plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    #plotitem.plot_var = v_velocity
    #plotitem.map_2d_to_1d = q_1d
    #plotitem.color = 'red'
    #plotitem.linewidth = 2.0
    #plotaxes.xlimits = [-6,70]
    #plotitem.show = True

    # figure of pressure
    plotfigure = plotdata.new_plotfigure(name='pressure', figno=7)
    plotaxes = plotfigure.new_plotaxes()
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = digplot.pressure_lithohead
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'blue'
    plotitem.linewidth = 2.0
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = 0
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'red'
    plotitem.linewidth = 2.0
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = digplot.pressure_head
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'black'
    plotitem.linewidth = 2.0
    plotaxes.xlimits = [-6, 70]
    plotaxes.ylimits = [0, 2]
    plotitem.show = True

    # figure of effective stress
    plotfigure = plotdata.new_plotfigure(name='sigbed', figno=8)
    plotaxes = plotfigure.new_plotaxes()
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = digplot.sigbed
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'blue'
    plotitem.linewidth = 2.0
    plotitem.show = False

    # figure of kperm
    plotfigure = plotdata.new_plotfigure(name='kperm', figno=9)
    plotaxes = plotfigure.new_plotaxes()
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = digplot.kperm
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'blue'
    plotitem.linewidth = 2.0
    plotaxes.ylimits = [1.e-12, 1.e-7]
    plotaxes.afteraxes = logscale

    # figure of h log
    plotfigure = plotdata.new_plotfigure(name='small h', figno=10)
    plotaxes = plotfigure.new_plotaxes()
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = 0
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'blue'
    plotitem.linewidth = 2.0
    plotaxes.ylimits = [1.e-4, 1.e-1]
    plotaxes.afteraxes = logscale

    # Parameters used only when creating html and/or latex hardcopy
    # e.g., via pyclaw.plotters.frametools.printframes:

    plotdata.printfigs = True  # print figures
    plotdata.print_format = 'png'  # file format
    plotdata.print_framenos = np.array(range(0, 20))  # list of frames to print
    plotdata.print_fignos = 'all'  # list of figures to print
    plotdata.html = True  # create html files of plots?
    plotdata.html_homelink = '../README.html'
    plotdata.latex = True  # create latex file of plots?
    plotdata.latex_figsperline = 2  # layout of plots
    plotdata.latex_framesperline = 1  # layout of plots
    plotdata.latex_makepdf = False  # also run pdflatex?
    plotdata.print_gaugenos = []

    return plotdata
Beispiel #49
0
def run_case(solver, casepath):
    """Run a single case with specified solver."""
    import shutil
    import glob
    import subprocess

    solver = os.path.abspath(solver)
    casepath = os.path.abspath(casepath)
    out_path = os.path.join(casepath, "_output")

    logger.info("Preparing to run case %s", casepath)
    if os.path.isdir(out_path):

        # if casepath not in sys.path, add it
        if casepath != sys.path[0]:
            print(sys.path[0])
            sys.path.insert(0,
                            casepath)  # add case folder to module search path
        print(sys.path[0])

        # get rundata
        import setrun
        rundata = setrun.setrun()
        nframes = rundata.clawdata.num_output_times + 1
        del rundata
        del sys.modules["setrun"]
        del sys.path[0]

        nfiles = [
            len(glob.glob(os.path.join(out_path, "fort.t" + "[0-9]" * 4))),
            len(glob.glob(os.path.join(out_path, "fort.a" + "[0-9]" * 4))),
            len(glob.glob(os.path.join(out_path, "fort.b" + "[0-9]" * 4))),
            len(glob.glob(os.path.join(out_path, "fort.q" + "[0-9]" * 4)))
        ]

        # check if this case is already completed
        if all([n == nframes for n in nfiles]):
            logger.warning("Case %s seems to be already done. Skip it",
                           casepath)
            return

        logger.warning("Case %s is not complete. Remove outputs and re-run.",
                       casepath)
        shutil.rmtree(out_path)

    # make the output folder
    os.makedirs(out_path)

    # copy data files to output folder
    datafiles = glob.glob(os.path.join(casepath, "*.data"))
    for datafile in datafiles:
        base = os.path.basename(datafile)
        shutil.copyfile(datafile, os.path.join(out_path, base))

    # change directory to output directory
    orig_dir = os.getcwd()
    os.chdir(out_path)

    # run simulation
    logger.info("Runngin case %s", casepath)
    logger.info("STDOUT is redirected to %s",
                os.path.join(casepath, "stdout.txt"))
    logger.info("STDERR is redirected to %s",
                os.path.join(casepath, "stderr.txt"))
    stdout = open(os.path.join(casepath, "stdout.txt"), "w")
    stderr = open(os.path.join(casepath, "stderr.txt"), "w")

    job = subprocess.run([solver], stdout=stdout, stderr=stderr)

    stdout.close()
    stderr.close()

    try:
        job.check_returncode()
    except subprocess.CalledProcessError:
        logger.error(job.stderr.decode("UTF-8"))
        logger.error("Simulation case %s failed. Exit.", casepath)
        raise

    logger.info("Finished case %s", casepath)

    # go back to the original directory
    os.chdir(orig_dir)
Beispiel #50
0
        sys.exit(1)
    case_settings_dict = {}
    with open(case_settings_file) as f:
        for line in f:
            (key, val) = line.split("=")
            case_settings_dict[key] = val.rstrip()

    apply_datetime_stamp = case_settings_dict.get("APPLY_DATETIME_STAMP")
    datetime_stamp = case_settings_dict.get("DATETIME_STAMP")
    calendar_type = case_settings_dict.get("CALENDAR_TYPE")

    # load setup.py
    sys.path.insert(0, casepath) # add case folder to module search path
    import setrun # import the setrun.py

    rundata = setrun.setrun() # get ClawRunData object

    # computational domain
    x_domain_bg = rundata.clawdata.lower[0]
    x_domain_ed = rundata.clawdata.upper[0]
    y_domain_bg = rundata.clawdata.lower[1]
    y_domain_ed = rundata.clawdata.upper[1]

    # number of frames
    if args.frame_ed is not None:
        frame_ed = args.frame_ed + 1
    elif rundata.clawdata.output_style == 1:
        frame_ed = rundata.clawdata.num_output_times
        if rundata.clawdata.output_t0:
            frame_ed += 1
    elif rundata.clawdata.output_style == 2:
    def __init__(self, prefix, storm_directory, storm_object, wind_model,
                 amr_level, storm_ensemble_type, region, cmip5_model):
        r"""
        Initialize a LongIslandStormJob object.

        See :class:`LongIslandStormJob` for full documentation

        """

        super(LongIslandStormJob, self).__init__()

        self.email = None

        self.type = "storm-surge"
        self.storm_ensemble_type = storm_ensemble_type
        self.region = region

        self.storm_directory = storm_directory
        self.storm_object = storm_object

        #self.name = "%s-amr%s" %(wind_model, amr_level)
        self.name = "%s-amr%s" % (cmip5_model, amr_level)
        self.prefix = str(prefix).zfill(4)
        self.executable = 'xgeoclaw'

        # Data objects
        import setrun
        self.rundata = setrun.setrun()

        # Set rundata friction, surge, and clawdata variables
        self.rundata = setrun.setgeo(self.rundata)

        # Set surge data
        self.rundata.surge_data.storm_specification_type = wind_model

        #delta_t0 = self.storm_object.t[0] - self.storm_object.time_offset
        #self.rundata.clawdata.t0 = days2seconds(delta_t0.days)/2
        #self.rundata.clawdata.t0 = days2seconds(-0.5)
        self.rundata.clawdata.t0 = days2seconds(0.0)

        # clawdata.tfinal value is the entire length of the track in days
        print(self.storm_object.t[-1])
        print(self.storm_object.time_offset)
        delta_tf = self.storm_object.t[-1] - self.storm_object.time_offset
        self.rundata.clawdata.tfinal = days2seconds(delta_tf.days)

        # Set refinement
        self.rundata.amrdata.amr_levels_max = amr_level

        # Set regions data =
        # Long Island Region
        self.rundata.regiondata.regions = []
        self.rundata.regiondata.regions.append([
            1, 7, self.rundata.clawdata.t0, self.rundata.clawdata.tfinal,
            -74.1, -73.7, 40.55, 48.5
        ])

        # Set Gauge Data
        # for gauges append lines of the form  [gaugeno, x, y, t1, t2]
        self.rundata.gaugedata.gauges = []
        # Gauge 1
        #self.rundata.gaugedata.gauges.append([1, -73.84055, 40.44838,
        #                                    self.rundata.clawdata.t0,
        #                                    self.rundata.clawdata.tfinal])
        ## Gauge 2
        #self.rundata.gaugedata.gauges.append([2, -73.33605, 40.62581,
        #                                    self.rundata.clawdata.t0,
        #                                    self.rundata.clawdata.tfinal])
        #
        #self.rundata.gaugedata.gauges.append([3, -73.76252, 40.56637,
        #                                    self.rundata.clawdata.t0,
        #                                    self.rundata.clawdata.tfinal])
        #
        #self.rundata.gaugedata.gauges.append([4, -74.09573, 40.49226,
        #                                    self.rundata.clawdata.t0,
        #                                    self.rundata.clawdata.tfinal])
        #
        #self.rundata.gaugedata.gauges.append([5, -73.93428, 40.51212,
        #                                    self.rundata.clawdata.t0,
        #                                    self.rundata.clawdata.tfinal])
        #
        self.rundata.gaugedata.gauges.append([
            1, -73.82716, 40.47975, self.rundata.clawdata.t0,
            self.rundata.clawdata.tfinal
        ])

        self.rundata.gaugedata.gauges.append([
            2, -73.91643, 40.40659, self.rundata.clawdata.t0,
            self.rundata.clawdata.tfinal
        ])
        # Sea Gauge 1 for coasrse refinements
        self.rundata.gaugedata.gauges.append([
            3, -73.82854, 40.26235, self.rundata.clawdata.t0,
            self.rundata.clawdata.tfinal
        ])

        # Sea Gauge 2 for coarse refinements
        self.rundata.gaugedata.gauges.append([
            4, -73.49758, 40.46744, self.rundata.clawdata.t0,
            self.rundata.clawdata.tfinal
        ])
        # Include auxillary gauge data
        self.rundata.gaugedata.aux_out_fields = [4, 5, 6]

        # Set path to geoclaw storm file
        self.rundata.surge_data.storm_file = os.path.join(
            self.storm_directory, "%s_%s.storm" % (self.region, self.prefix))

        # Write storm data in geoclaw storm file
        self.storm_object.write(self.rundata.surge_data.storm_file,
                                file_format="geoclaw")
Beispiel #52
0
def gauges2kml(rundata=None, fname='gauges.kml', verbose=True):
    """

    Create a KML marker for each gauge specified for a GeoClaw run.

    :Inputs:

      - *rundata* - an object of class *ClawRunData* or None

        If *rundata==None*, try to create based on executing function *setrun*
        from the `setrun.py` file in the current directory.

      - *fname* (str) - resulting kml file.

      - *verbose* (bool) - If *True*, print out info about each region found


    :Example:

        >>> from clawpack.geoclaw import kmltools
        >>> kmltools.gauges2kml()

    is equivalent to:

        >>> from clawpack.geoclaw import kmltools
        >>> from setrun import setrun
        >>> rundata = setrun()
        >>> kmltools.gauges2kml(rundata)

    By default this creates a file named *gauges.kml* that can be opened in
    Google Earth.

    """

    if rundata is None:
        try:
            import setrun
            reload(setrun)
            rundata = setrun.setrun()
        except:
            raise IOError("*** cannot execute setrun file")

    elev = 0.
    kml_text = kml_header(fname)

    gauges = rundata.gaugedata.gauges
    if len(gauges) == 0 and verbose:
        print("No gauges found in setrun.py")

    for rnum, gauge in enumerate(gauges):
        t1, t2 = gauge[3:5]
        x1, y1 = gauge[1:3]
        gaugeno = gauge[0]
        if verbose:
            print("Gauge %i: %10.6f  %10.6f  \n" % (gaugeno,x1,y1) \
                    + "  t1 = %10.1f,  t2 = %10.1f" % (t1,t2))
        mapping = {}
        mapping['gaugeno'] = gaugeno
        mapping['t1'] = t1
        mapping['t2'] = t2
        mapping['x1'] = x1
        mapping['y1'] = y1
        mapping['elev'] = elev
        mapping['name'] = 'Gauge %i' % rnum
        description = "  t1 = %g, t2 = %g\n" % (t1,t2) \
            + "  x1 = %g, y1 = %g\n" % (x1,y1)
        mapping['desc'] = description

        gauge_text = kml_gauge(mapping)
        kml_text = kml_text + gauge_text
    kml_text = kml_text + kml_footer()
    kml_file = open(fname, 'w')
    kml_file.write(kml_text)
    kml_file.close()
    if verbose:
        print("Created ", fname)
Beispiel #53
0
    def __init__(self, slips, run_number=1): 
        r"""
        Initialize a FaultJob object.
        
        See :class:`FaultJob` for full documentation
        
        """ 

        super(FaultJob, self).__init__()

        self.run_number = run_number

        # Create fault
        # Based on UCSB reconstruction and assumption of single subfault
        # Lengths are based on num_fault_segments * dx * m/km in each direction
        #
        # Top edge    Bottom edge
        #   a ----------- b          ^ 
        #   |             |          |         ^
        #   |             |          |         |
        #   |             |          |         | along-strike direction
        #   |             |          |         |
        #   0------1------2          | length  |
        #   |             |          |
        #   |             |          |
        #   |             |          |
        #   |             |          |
        #   d ----------- c          v
        #   <------------->
        #       width
        # <-- up dip direction
        #
        #  Given
        #      Long            Lat             Depth
        #  a = 144.56380       39.66720        7.50520
        #  b = 140.76530       36.15960       41.96770
        #  c = 142.43800       40.21080       41.96770
        #  d = 142.89110       35.61610        7.50520
        #  Computed
        #      Long            Lat             Depth
        #  0 = 143.72745       37.64165        7.50520
        # Comparison Fault System
        UCSB_fault = dtopotools.UCSBFault('./UCSB_model3_subfault.txt')

        # Use data from the reconstruced UCSB fault to setup our fault system
        # Calculate average quantities across all subfaults
        ave_rake = 0.0
        ave_strike = 0.0
        ave_slip = 0.0
        for subfault in UCSB_fault.subfaults:
            ave_rake = subfault.rake
            ave_strike = subfault.strike
            ave_slip = subfault.slip

        ave_rake /= len(UCSB_fault.subfaults)
        ave_strike /= len(UCSB_fault.subfaults)
        ave_slip /= len(UCSB_fault.subfaults)

        # Base subfault
        self.base_subfault = dtopotools.SubFault()
        self.base_subfault.strike = 198.0
        self.base_subfault.length = 19 * 25.0 * 1000.0
        self.base_subfault.width = 10 * 20.0 * 1000.0
        self.base_subfault.depth = 7.50520 * 1000.0
        self.base_subfault.slip = ave_slip
        self.base_subfault.rake = 90.0
        self.base_subfault.dip = 10.0
        self.base_subfault.latitude = 37.64165
        self.base_subfault.longitude = 143.72745
        self.base_subfault.coordinate_specification = "top center"

        # Create base subdivided fault
        self.fault = dtopotools.SubdividedPlaneFault(self.base_subfault, 
                                                     nstrike=3, ndip=2)
        for (k, subfault) in enumerate(self.fault.subfaults):
            subfault.slip = slips[k]

        self.type = "tsunami"
        self.name = "final-tohoku-inversion"
        self.prefix = "fault_%s" % self.run_number
        self.executable = 'xgeoclaw'

        # Data objects
        import setrun
        self.rundata = setrun.setrun()

        # No variable friction for the time being
        self.rundata.friction_data.variable_friction = False

        # Replace dtopo file with our own
        self.dtopo_path = 'fault_s%s.tt3' % self.base_subfault.slip
        self.rundata.dtopo_data.dtopofiles = [[3, 4, 4, self.dtopo_path]]
Beispiel #54
0
def run_code_or_restart():

    import time
    tm = time.localtime()
    year = str(tm[0]).zfill(4)
    month = str(tm[1]).zfill(2)
    day = str(tm[2]).zfill(2)
    hour = str(tm[3]).zfill(2)
    minute = str(tm[4]).zfill(2)
    second = str(tm[5]).zfill(2)
    timestamp = '%s-%s-%s-%s%s%s'  % (year,month,day,hour,minute,second)

    finished, latest, t_latest = examine_outdir(outdir)

    if finished:
        print("Code has finished running, remove %s to run again" % outdir)
        return

    restart = (latest is not None)

    fname_output = 'run_output.txt'
    fname_errors = 'run_errors.txt'

    if restart:
        print("Will attempt to restart using checkpoint file %s at t = %s" \
                % (latest, t_latest))
        print("Appending output stream to %s" % fname_output)
        access = 'a'
    else:
        print("Will run code -- no restart")
        print("Writing output stream to %s" % fname_output)
        access = 'w'

    fout = open(fname_output, access)
    ferr = open(fname_errors, access)

    if restart:
        fout.flush()
        fout.write("\n=========== RESTART =============\n" + \
                "Local time: %s\n" % timestamp + \
                "Will attempt to restart using checkpoint file %s at t = %s\n" \
                % (latest, t_latest))
        fout.flush()
        make_args = ['make','output','RESTART=True']
    else:
        make_args = ['make','output']

    #if restart:
    #    No longer need to do this since new restart now adds to gauge*.txt files
    #    fortgauge = os.path.join(outdir,'fort.gauge')
    #    fortgauge2 = os.path.join(outdir,'fort.gauge_%s' % timestamp)
    #    os.system("mv %s %s" % (fortgauge,fortgauge2))
    #    fout.write("Moving %s to %s \n" % (fortgauge,fortgauge2))
    #    fout.flush()

    rundata = setrun('amrclaw')
    rundata.clawdata.restart = restart
    rundata.clawdata.restart_file = 'fort.chk' + str(latest)
    if restart:
        rundata.clawdata.output_t0 = False  # to avoid plotting at restart times
    rundata.write()
    
    job = subprocess.Popen(make_args, stdout=fout,stderr=ferr,env=env)
    return_code = job.wait()
    
    if return_code == 0:
        print("Successful run\n")
    else:
        print("Problem running code\n")
    print("See %s and %s" % (fname_output,fname_errors))
    
    fout.close()
    ferr.close()
Beispiel #55
0
def regions2kml(rundata=None,fname='regions.kml',verbose=True,combined=True):

    """
    Create a KML box for each AMR region specified for a GeoClaw run.

    :Inputs:

      - *rundata* - an object of class *ClawRunData* or None

        If *rundata==None*, try to create based on executing function *setrun*
        from the `setrun.py` file in the current directory.

      - *fname* (str) - resulting kml file.

      - *verbose* (bool) - If *True*, print out info about each region found

      - *combined* (bool) - If *True*, combine into single kml file with
        name given by *fname*.  This is the default. 
        If False, *fname* is ignored and individual files are created for
        each region with names are Domain.kml, Region00.kml, etc.
        These will show up separately in GoogleEarth so they can be turned
        on or off individually.

    First create a box for the entire domain (in red) and then a box
    for each region (in white).

    :Example:

        >>> from clawpack.geoclaw import kmltools
        >>> kmltools.regions2kml()

    is equivalent to:

        >>> from clawpack.geoclaw import kmltools
        >>> from setrun import setrun
        >>> rundata = setrun()
        >>> kmltools.regions2kml(rundata)

    By default this creates a file named *regions.kml* that can be opened in
    Google Earth.

    """

    from numpy import cos,pi,floor

    if rundata is None:
        try:
            import setrun
            reload(setrun)
            rundata = setrun.setrun()
        except:
            raise IOError("*** cannot execute setrun file")

    clawdata = rundata.clawdata
    x1,y1 = clawdata.lower[0:]
    x2,y2 = clawdata.upper[0:]
    description = "  x1 = %g, x2 = %g\n" % (x1,x2) \
            + "  y1 = %g, y2 = %g\n" % (y1,y2)

    mx,my = clawdata.num_cells[0:]
    dx = (x2-x1)/float(mx)
    dx_meters = dx*111e3*cos(pi*0.5*(y1+y2)/180.)
    dy = (y2-y1)/float(my)
    dy_meters = dy*111e3
    if verbose:
        print("Domain:   %10.6f  %10.6f  %10.6f  %10.6f" % (x1,x2,y1,y2))
    dx_deg,dx_min,dx_sec = deg2dms(dx)
    dy_deg,dy_min,dy_sec = deg2dms(dy)
    #print "Level 1 resolution:  dx = %g deg, %g min, %g sec = %g meters" \
    #   % (dx_deg,dx_min,dx_sec,dx_meters)
    levtext = "Level 1 resolution:  dy = %g deg, %g min, %g sec = %g meters\n" \
        % (dy_deg,dy_min,dy_sec,dy_meters)
    if verbose:
        print(levtext)
    description = description + levtext

    amr_levels_max = rundata.amrdata.amr_levels_max
    refinement_ratios_y = rundata.amrdata.refinement_ratios_y
    num_ref_ratios = len(refinement_ratios_y)
    if amr_levels_max > num_ref_ratios+1:
        raise IOError("*** Too few refinement ratios specified for " \
            + "amr_levels_max = %i" % amr_levels_max)
    dy_levels = (num_ref_ratios+1) * [dy]
    for k,r in enumerate(refinement_ratios_y):
        level = k+2
        dy = dy_levels[k] / r
        dy_levels[k+1] = dy
        dy_meters = dy*111e3
        dy_deg,dy_min,dy_sec = deg2dms(dy)
        levtext = "Level %s resolution:  dy = %g deg, %g min, %g sec = %g meters  (refined by %i)\n" \
                % (level,dy_deg,dy_min,dy_sec,dy_meters,r)
        if verbose:
            print(levtext)
        description = description + levtext

    if verbose:
        print("Allowing maximum of %i levels" % amr_levels_max)

    elev = 0.
    if not combined:
        fname = 'Domain.kml'

    kml_text = kml_header(fname)

    mapping = {}
    mapping['x1'] = x1
    mapping['x2'] = x2
    mapping['y1'] = y1
    mapping['y2'] = y2
    mapping['elev'] = elev
    mapping['name'] = 'Computational Domain'
    mapping['desc'] = description
    mapping['color'] = "0000FF"  # red
    mapping['width'] = 2

    region_text = kml_region(mapping)
    kml_text = kml_text + region_text

    if not combined:
        kml_text = kml_text + kml_footer()
        kml_file = open(fname,'w')
        kml_file.write(kml_text)
        kml_file.close()
        if verbose:
            print("Created ",fname)

            

    regions = rundata.regiondata.regions
    if len(regions)==0 and verbose:
        print("No regions found in setrun.py")


    for rnum,region in enumerate(regions):
        if not combined:
            fname = 'Region_%s.kml' % str(rnum).zfill(2)
            kml_text = kml_header(fname)

        minlevel,maxlevel = region[0:2]
        t1,t2 = region[2:4]
        x1,x2,y1,y2 = region[4:]

        if verbose:
            print("Region %i: %10.6f  %10.6f  %10.6f  %10.6f" \
                    % (rnum,x1,x2,y1,y2))
            print("           minlevel = %i,  maxlevel = %i" \
                    % (minlevel,maxlevel) \
                    + "  t1 = %10.1f,  t2 = %10.1f" % (t1,t2))
        mapping = {}
        mapping['minlevel'] = minlevel
        mapping['maxlevel'] = maxlevel
        mapping['t1'] = t1
        mapping['t2'] = t2
        mapping['x1'] = x1
        mapping['x2'] = x2
        mapping['y1'] = y1
        mapping['y2'] = y2
        mapping['elev'] = elev
        mapping['name'] = 'Region %i' % rnum
        description = "minlevel = %i, maxlevel = %i\n" % (minlevel,maxlevel) \
            + "  t1 = %g, t2 = %g\n" % (t1,t2) \
            + "  x1 = %g, x2 = %g\n" % (x1,x2) \
            + "  y1 = %g, y2 = %g\n\n" % (y1,y2)
        if len(dy_levels) >= minlevel:
            dy = dy_levels[minlevel-1]
            dy_deg,dy_min,dy_sec = deg2dms(dy)
            dy_meters = dy*111e3
            levtext = "Level %s resolution:  \ndy = %g deg, %g min, %g sec \n= %g meters\n" \
                    % (minlevel,dy_deg,dy_min,dy_sec,dy_meters)
            description = description + levtext
        if (maxlevel > minlevel) and (len(dy_levels) >= maxlevel):
            dy = dy_levels[maxlevel-1]
            dy_deg,dy_min,dy_sec = deg2dms(dy)
            dy_meters = dy*111e3
            levtext = "\nLevel %s resolution:  \ndy = %g deg, %g min, %g sec \n= %g meters\n" \
                    % (maxlevel,dy_deg,dy_min,dy_sec,dy_meters)
            description = description + levtext
        mapping['desc'] = description
        mapping['color'] = "FFFFFF"  # white
        mapping['width'] = 3

        region_text = kml_region(mapping)
        kml_text = kml_text + region_text
        if not combined:
            kml_text = kml_text + kml_footer()
            kml_file = open(fname,'w')
            kml_file.write(kml_text)
            kml_file.close()
            if verbose:
                print("Created ",fname)

    if combined:
        kml_text = kml_text + kml_footer()
        kml_file = open(fname,'w')
        kml_file.write(kml_text)
        kml_file.close()
        if verbose:
            print("Created ",fname)
Beispiel #56
0
def regions2kml(rundata=None,fname='regions.kml'):

    """
    Read in the AMR regions from setrun.py and create a kml box for each.
    First create a box for the entire domain (in red) and then a box
    for each region (in white).
    """

    from numpy import cos,pi,floor

    if rundata is None:
        try:
            import setrun
            reload(setrun)
            rundata = setrun.setrun()
        except:
            raise IOError("*** cannot execute setrun file")

    clawdata = rundata.clawdata
    x1,y1 = clawdata.lower[0:]
    x2,y2 = clawdata.upper[0:]
    description = "  x1 = %g, x2 = %g\n" % (x1,x2) \
            + "  y1 = %g, y2 = %g\n" % (y1,y2) 

    mx,my = clawdata.num_cells[0:]
    dx = (x2-x1)/float(mx)
    dx_meters = dx*111e3*cos(pi*0.5*(y1+y2)/180.)
    dy = (y2-y1)/float(my)
    dy_meters = dy*111e3
    print "Domain:   %10.6f  %10.6f  %10.6f  %10.6f" % (x1,x2,y1,y2)
    dx_deg,dx_min,dx_sec = deg2dms(dx)
    dy_deg,dy_min,dy_sec = deg2dms(dy)
    #print "Level 1 resolution:  dx = %g deg, %g min, %g sec = %g meters" \
    #   % (dx_deg,dx_min,dx_sec,dx_meters)
    levtext = "Level 1 resolution:  dy = %g deg, %g min, %g sec = %g meters\n" \
        % (dy_deg,dy_min,dy_sec,dy_meters)
    print levtext
    description = description + levtext

    amr_levels_max = rundata.amrdata.amr_levels_max
    refinement_ratios_y = rundata.amrdata.refinement_ratios_y
    num_ref_ratios = len(refinement_ratios_y)
    if amr_levels_max > num_ref_ratios+1:
        raise IOError("*** Too few refinement ratios specified for " \
            + "amr_levels_max = %i" % amr_levels_max)
    dy_levels = (num_ref_ratios+1) * [dy]
    for k,r in enumerate(refinement_ratios_y):
        level = k+2
        dy = dy_levels[k] / r
        dy_levels[k+1] = dy
        dy_meters = dy*111e3
        dy_deg,dy_min,dy_sec = deg2dms(dy)
        levtext = "Level %s resolution:  dy = %g deg, %g min, %g sec = %g meters  (refined by %i)\n" \
                % (level,dy_deg,dy_min,dy_sec,dy_meters,r)
        print levtext
        description = description + levtext

    print "Allowing maximum of %i levels" % amr_levels_max

    elev = 0.
    kml_text = kml_header()
    
    mapping = {}
    mapping['x1'] = x1
    mapping['x2'] = x2
    mapping['y1'] = y1
    mapping['y2'] = y2
    mapping['elev'] = elev
    mapping['name'] = 'Computational Domain'
    mapping['desc'] = description
    mapping['color'] = "0000FF"  # red

    region_text = kml_region(mapping)
    kml_text = kml_text + region_text

    regions = rundata.regiondata.regions
    if len(regions)==0:
        print "No regions found in setrun.py"


    for rnum,region in enumerate(regions):
        minlevel,maxlevel = region[0:2]
        t1,t2 = region[2:4]
        x1,x2,y1,y2 = region[4:]
        print "Region %i: %10.6f  %10.6f  %10.6f  %10.6f" % (rnum,x1,x2,y1,y2)
        print "           minlevel = %i,  maxlevel = %i" % (minlevel,maxlevel) \
                + "  t1 = %10.1f,  t2 = %10.1f" % (t1,t2)
        mapping = {}
        mapping['minlevel'] = minlevel
        mapping['maxlevel'] = maxlevel
        mapping['t1'] = t1
        mapping['t2'] = t2
        mapping['x1'] = x1
        mapping['x2'] = x2
        mapping['y1'] = y1
        mapping['y2'] = y2
        mapping['elev'] = elev
        mapping['name'] = 'Region %i' % rnum
        description = "minlevel = %i, maxlevel = %i\n" % (minlevel,maxlevel) \
            + "  t1 = %g, t2 = %g\n" % (t1,t2) \
            + "  x1 = %g, x2 = %g\n" % (x1,x2) \
            + "  y1 = %g, y2 = %g\n\n" % (y1,y2) 
        if len(dy_levels) >= minlevel:
            dy = dy_levels[minlevel-1]
            dy_deg,dy_min,dy_sec = deg2dms(dy)
            dy_meters = dy*111e3
            levtext = "Level %s resolution:  \ndy = %g deg, %g min, %g sec \n= %g meters\n" \
                    % (minlevel,dy_deg,dy_min,dy_sec,dy_meters)
            description = description + levtext
        if (maxlevel > minlevel) and (len(dy_levels) >= maxlevel):
            dy = dy_levels[maxlevel-1]
            dy_deg,dy_min,dy_sec = deg2dms(dy)
            dy_meters = dy*111e3
            levtext = "\nLevel %s resolution:  \ndy = %g deg, %g min, %g sec \n= %g meters\n" \
                    % (maxlevel,dy_deg,dy_min,dy_sec,dy_meters)
            description = description + levtext
        mapping['desc'] = description
        mapping['color'] = "FFFFFF"  # white

        region_text = kml_region(mapping)
        kml_text = kml_text + region_text
    kml_text = kml_text + kml_footer()
    kml_file = open(fname,'w')
    kml_file.write(kml_text)
    kml_file.close()
    print "Created ",fname
Beispiel #57
0
def gauges2kml(rundata=None, fname='gauges.kml', verbose=True):

    """

    Create a KML marker for each gauge specified for a GeoClaw run.

    :Inputs:

      - *rundata* - an object of class *ClawRunData* or None

        If *rundata==None*, try to create based on executing function *setrun*
        from the `setrun.py` file in the current directory.

      - *fname* (str) - resulting kml file.

      - *verbose* (bool) - If *True*, print out info about each region found


    :Example:

        >>> from clawpack.geoclaw import kmltools
        >>> kmltools.gauges2kml()

    is equivalent to:

        >>> from clawpack.geoclaw import kmltools
        >>> from setrun import setrun
        >>> rundata = setrun()
        >>> kmltools.gauges2kml(rundata)

    By default this creates a file named *gauges.kml* that can be opened in
    Google Earth.

    """


    if rundata is None:
        try:
            import setrun
            reload(setrun)
            rundata = setrun.setrun()
        except:
            raise IOError("*** cannot execute setrun file")

    elev = 0.
    kml_text = kml_header(fname)


    gauges = rundata.gaugedata.gauges
    if len(gauges)==0 and verbose:
        print("No gauges found in setrun.py")


    for rnum,gauge in enumerate(gauges):
        t1,t2 = gauge[3:5]
        x1,y1 = gauge[1:3]
        gaugeno = gauge[0]
        if verbose:
            print("Gauge %i: %10.6f  %10.6f  \n" % (gaugeno,x1,y1) \
                    + "  t1 = %10.1f,  t2 = %10.1f" % (t1,t2))
        mapping = {}
        mapping['gaugeno'] = gaugeno
        mapping['t1'] = t1
        mapping['t2'] = t2
        mapping['x1'] = x1
        mapping['y1'] = y1
        mapping['elev'] = elev
        mapping['name'] = 'Gauge %i' % rnum
        description = "  t1 = %g, t2 = %g\n" % (t1,t2) \
            + "  x1 = %g, y1 = %g\n" % (x1,y1)
        mapping['desc'] = description

        gauge_text = kml_gauge(mapping)
        kml_text = kml_text + gauge_text
    kml_text = kml_text + kml_footer()
    kml_file = open(fname,'w')
    kml_file.write(kml_text)
    kml_file.close()
    if verbose:
        print("Created ",fname)
Beispiel #58
0
#import clawpack.geoclaw.shallow_1d.plot as geoplot

#let's try something
import sys
sys.path.insert(0,'/home/jog/Software_Development/uw/Riemann/roe/src/python')
import plot as geoplot
#from src.python import plot as geoplot

import setrun
rundata=setrun.setrun()


def setplot(plotdata):
    
    xlims=[-50.0,100.0]
    ylims=[-1,1.5]

    plotdata.clearfigures()

    plotfigure = plotdata.new_plotfigure(name='surface height', figno=0)
    
    #first plot the results from the full solver
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.axescmd='subplot(3,1,1)'
    plotaxes.xlimits = xlims
    plotaxes.ylimits = ylims
    plotaxes.title = 'full solver'

    plotitem = plotaxes.new_plotitem(plot_type='1d_fill_between')
    plotitem.plot_var = geoplot.surface_full
Beispiel #59
0
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.

    """
    import setrun

    setrundata = setrun.setrun()

    plotdata.clearfigures()  # clear any old figures,axes,items data


    def q_1d_fill(current_data):
        X = current_data.x
        Y = current_data.y
        a2dvar = current_data.var
        a2dvar2 = current_data.var2
        dy = current_data.dy

        #yind = np.where(np.abs(Y[0,:]-1.0)<=dy/2.0)[0]
        #xind = np.where(X[:,0]> -1.e10)[0]

        if (current_data.grid.level==2):
            yind = np.where(np.abs(Y[0,:]-1.0)<=dy)[0]
            xind = np.where(X[:,0]> -1.e10)[0]
        else:
            yind = np.where(Y[0,:]>1.e10)[0]
            xind = np.where(X[:,0]>1.e10)[0]

        x = X[np.ix_(xind,yind)]
        a1dvar = a2dvar[np.ix_(xind,yind)]#-x*np.sin(31.*np.pi/180.0)
        a1dvar2 = a2dvar2[np.ix_(xind,yind)]#-x*np.sin(31.*np.pi/180.0)
        #pdb.set_trace() #<-----------------------------

        return x,a1dvar,a1dvar2

    def q_1d(current_data):
        X = current_data.x
        Y = current_data.y
        dy = current_data.dy
        a2dvar = current_data.var

        if (current_data.grid.level==2):
            yind = np.where(np.abs(Y[0,:]-1.0)<=dy)[0]
            xind = np.where(X[:,0]> -1.e10)[0]
        else:
            yind = np.where(Y[0,:]>1.e10)[0]
            xind = np.where(X[:,0]>1.e10)[0]

        x = X[np.ix_(xind,yind)]
        a1dvar = a2dvar[np.ix_(xind,yind)]#-x*np.sin(31.*np.pi/180.0)

        return x,a1dvar

    def fixup(current_data):
        import pylab

        t=current_data.t
        pylab.title('')
        #pylab.xticks([-5.9,-3,0,2.9],('-6.0','-3.0','0.0','3.0'),fontsize=18)
        #pylab.yticks([0,1.0,1.9],('0.0','1.0','2.0'),fontsize=18)
        pylab.text(-5.5,1.9,'t = %6.2f s'% (t),fontsize=20, style = 'italic', \
            horizontalalignment='left',verticalalignment='top', \
            rotation = 31.0)
        #pdb.set_trace()
        #axx = pylab.gca()
        #scalebars.add_scalebar(axx)
        xbase = np.linspace(-6.0,0.0,5000)
        ybase = 0.0*xbase
        ybase[-1] = 0.65
        pylab.plot(xbase,ybase,'k-')
        #in front of ramp
        xbase = np.linspace(0.0,3.0,5000)
        ybase = 0.0*xbase
        pylab.plot(xbase,ybase,'k-')
        pylab.gcf().subplots_adjust(bottom=0.15)
        #pylab.tight_layout()
        return current_data

    def logscale(current_data):
        pplt.gca().set_yscale('log')
        return current_data


    def plot_lagrangian(current_data):

        #lagrangian dots

        if current_data.grid.level < 2:
            return current_data

        t=current_data.t
        #(allgaugedata,xgauges,ygauges,gauge_nums) = cg.getgaugedata('../_output/fort.gauge','../_output/setgauges.data')
        #pdb.set_trace()
        x0Lagrangian=[0.0975 -3.5 + 0.65*np.sin(theta),-2.3+0.08+ 0.65*np.sin(theta),-1.1+0.0512+ 0.65*np.sin(theta)]
        xColor = ['c*','rp','m*']
        vplacement=[0.5,0.15,0.5]
        T = np.linspace(0.0,t,500)
        X = current_data.x
        Y = current_data.y
        dy = current_data.dy
        dx = current_data.dx
        h2d = current_data.q[:,:,0]
        topo2d = digplot.topo(current_data)

        for x0ind in xrange(len(x0Lagrangian)):
            x0 = x0Lagrangian[x0ind]

            Xoft = cg.Lagrangian_Xoft(allgaugedata,xgauges,gauge_nums,x0,T)
            xnow = Xoft[-1]

            if ((current_data.xupper+0.5*dx> xnow)&(current_data.xlower-0.5*dx<=xnow)):
                yind = np.where(np.abs(Y[0,:]-1.0)<=dy)[0]
                xind = np.where(X[:,0]> xnow)[0]
            else:
                yind = np.where(Y[0,:]>1.e10)[0]
                xind = np.where(X[:,0]>1.e10)[0]

            x = X[np.ix_(xind,yind)]
            #pdb.set_trace()
            if (xind.any()&yind.any()):
                h1d = h2d[np.ix_(xind,yind)]#-x*np.sin(31.*np.pi/180.0)
                topo1d = topo2d[np.ix_(xind,yind)]
                h1d = h1d.flatten()
                topo1d = topo1d.flatten()
                zcoord = topo1d[0] + vplacement[x0ind]*h1d[0]
                if x0ind==1:
                    zcoord = topo1d[0] + 0.1
                #pdb.set_trace()
                pylab.plot(xnow,zcoord,xColor[x0ind],markersize=14)

        return current_data

    

    # Figure for surface elevation with concentration
    plotfigure = plotdata.new_plotfigure(name='Surface3', figno=0)
    plotfigure.kwargs = {'figsize':(9,2.2),'frameon':False}
    plotfigure.tight_layout = True
#    plotfigure.clf_each_frame = False
    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    #plotaxes.xlimits = [-6.0,130]
    plotaxes.ylimits = [-0.2,2.0]#'auto' #[-.1,2.0]
    plotaxes.kwargs = {'frameon':'False','axis':'off'}
    #plotaxes.afteraxes = fixup
    # Set up for item on these axes: (plot tan depth)
    plotitem = plotaxes.new_plotitem(plot_type='1d_fill_between_from_2d_data')
    plotitem.plot_var = digplot.topo
    plotitem.plot_var2 = digplot.eta
    plotitem.map_2d_to_1d = q_1d_fill
    #plotitem.amr_gridlines_show = [1,1,1]
    plotitem.color = 'tan'
    # Set up for item on these axes: (plot red fill for coarse concentration)
    plotitem = plotaxes.new_plotitem(plot_type='1d_fill_between_from_2d_data')
    plotitem.plot_var = digplot.topo
    plotitem.plot_var2 = 5
    plotitem.map_2d_to_1d = q_1d_fill
    #plotitem.amr_gridlines_show = [1,1,1]
    plotitem.color = 'red'
    # Set up for item on these axes: (dark line for topography)
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = digplot.topo
    plotitem.map_2d_to_1d = q_1d
    plotitem.linestyle = '-'
    plotitem.color = 'black'
    plotitem.linewidth = 2.0
    plotitem.show = True


    # Figure for surface elevation
    plotfigure = plotdata.new_plotfigure(name='Surface', figno=1)
    plotfigure.kwargs = {'figsize':(9,2.2),'frameon':False}
    plotfigure.tight_layout = True
#    plotfigure.clf_each_frame = False

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    #plotaxes.xlimits = [-6.0,3.0]
    #plotaxes.ylimits = [-0.2,2.0]#'auto' #[-.1,2.0]
    plotaxes.xlimits = [80.0,113.0]
    plotaxes.ylimits = [-0.2,2.0]
    plotaxes.kwargs = {'frameon':'False','axis':'off'}
    plotaxes.afteraxes = fixup



    # Set up for item on these axes: (plot tan depth)
    plotitem = plotaxes.new_plotitem(plot_type='1d_fill_between_from_2d_data')
    plotitem.plot_var = digplot.topo
    plotitem.plot_var2 = digplot.eta
    plotitem.map_2d_to_1d = q_1d_fill
    #plotitem.amr_gridlines_show = [1,1,1]


    plotitem.color = 'tan'

    # Set up for item on these axes: (plot blue fill for pressure)
    plotitem = plotaxes.new_plotitem(plot_type='1d_fill_between_from_2d_data')
    plotitem.plot_var = digplot.topo
    plotitem.plot_var2 = digplot.pressure_lithohead_eta
    plotitem.map_2d_to_1d = q_1d_fill
    #plotitem.amr_gridlines_show = [1,1,1]
    plotitem.color = 'blue'

    # Set up for item on these axes: (dark line for topography)
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = digplot.topo
    plotitem.map_2d_to_1d = q_1d
    plotitem.linestyle = '-'
    plotitem.color = 'black'
    plotitem.linewidth = 2.0
    plotitem.show = True

    # Set up for lagrangian points
    #plotitem = plotaxes.new_plotitem(plot_type = '2d_empty')
    #plotitem.aftergrid = plot_lagrangian

    plotitem.show = True


    # figure of surface
    plotfigure = plotdata.new_plotfigure(name='Surface_2', figno=2)
    plotaxes = plotfigure.new_plotaxes()
    plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor')
    #plotaxes.xlimits = [-6.0,130.0]
    #plotaxes.ylimits = [-2.0,4.0]
    plotaxes.xlimits = [80,110.0]
    plotaxes.ylimits = [-2.0,4.0]
    plotitem.plot_var = 0#digplot.pressure_head
    plotitem.pcolor_cmin = 0.0
    plotitem.pcolor_cmax = 1.9
    plotitem.amr_gridlines_show = [1,1,0]
    #plotitem.amr_gridedges_show = [1 1 1]

    plotitem.show = False

    # figure of m vs. m_eqn
    plotfigure = plotdata.new_plotfigure(name='meqn', figno=3)
    plotaxes = plotfigure.new_plotaxes()
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = digplot.m_eqn
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'red'
    plotitem.linewidth = 2.0
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = digplot.solid_frac
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'black'
    plotitem.linewidth = 2.0
    plotaxes.ylimits = [0.5,0.7]
    plotaxes.xlimits = [-6,130]
    plotitem.show = True

    # figure of rho
    plotfigure = plotdata.new_plotfigure(name='rho', figno=4)
    plotaxes = plotfigure.new_plotaxes()
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = digplot.density
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'red'
    plotitem.linewidth = 2.0
    plotaxes.xlimits = [-6,130]
    plotitem.show = False

    # figure of Iv
    plotfigure = plotdata.new_plotfigure(name='Iv', figno=5)
    plotaxes = plotfigure.new_plotaxes()
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = digplot.Iv
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'red'
    plotitem.linewidth = 2.0
    plotaxes.xlimits = [-6,130]
    plotaxes.ylimits = [.00,.0025]
    plotitem.show = True

    # figure of u,v
    plotfigure = plotdata.new_plotfigure(name='uv', figno=6)
    plotaxes = plotfigure.new_plotaxes()
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = digplot.u_velocity
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'blue'
    plotitem.linewidth = 2.0
    plotaxes.xlimits = [-6,140]
    #plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    #plotitem.plot_var = v_velocity
    #plotitem.map_2d_to_1d = q_1d
    #plotitem.color = 'red'
    #plotitem.linewidth = 2.0
    #plotaxes.xlimits = [-6,130]
    #plotitem.show = True

    # figure of pressure
    plotfigure = plotdata.new_plotfigure(name='pressure', figno=7)
    plotaxes = plotfigure.new_plotaxes()
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = digplot.pressure_lithohead
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'blue'
    plotitem.linewidth = 2.0
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = 0
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'red'
    plotitem.linewidth = 2.0
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = digplot.pressure_head
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'black'
    plotitem.linewidth = 2.0
    plotaxes.xlimits = [-6,130]
    plotaxes.ylimits = [0,2]
    plotitem.show = True

    # figure of effective stress
    plotfigure = plotdata.new_plotfigure(name='sigbed', figno=8)
    plotaxes = plotfigure.new_plotaxes()
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = digplot.sigbed
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'blue'
    plotitem.linewidth = 2.0
    plotitem.show = False

    
    # figure of kperm
    plotfigure = plotdata.new_plotfigure(name='kperm', figno=9)
    plotaxes = plotfigure.new_plotaxes()
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = digplot.kperm_adjusted
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'blue'
    plotitem.linewidth = 2.0
    plotaxes.xlimits = [-6,130]
    plotaxes.ylimits = [1.e-12,1.e-7]
    plotaxes.afteraxes = logscale

    # figure of h log
    plotfigure = plotdata.new_plotfigure(name='small h', figno=10)
    plotaxes = plotfigure.new_plotaxes()
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.plot_var = 0
    plotitem.map_2d_to_1d = q_1d
    plotitem.color = 'blue'
    plotitem.linewidth = 2.0
    plotaxes.ylimits = [1.e-4,1.e1]
    plotaxes.xlimits = [-6,140]

    plotaxes.afteraxes = logscale
    

    # Parameters used only when creating html and/or latex hardcopy
    # e.g., via pyclaw.plotters.frametools.printframes:

    plotdata.printfigs = True                # print figures
    plotdata.print_format = 'png'            # file format
    plotdata.print_framenos = 'all' #[0,2,4,6,8,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150]       # list of frames to print
    plotdata.print_fignos = 'all'            # list of figures to print
    plotdata.html = True                     # create html files of plots?
    plotdata.html_homelink = '../README.html'
    plotdata.latex = True                    # create latex file of plots?
    plotdata.latex_figsperline = 2           # layout of plots
    plotdata.latex_framesperline = 1         # layout of plots
    plotdata.latex_makepdf = False           # also run pdflatex?
    plotdata.print_gaugenos = []

    return plotdata