Exemplo n.º 1
0
    def solve(self):
        """Solve the SSA by calling the underlying PISM :cpp:class:`SSA`'s
        :cpp:member:`update` method. Returns the solution vector (owned by
        self.ssa, but you should not need to know about ownership).

        """
        vecs = self.modeldata.vecs

        # make sure vecs is locked!
        self.ssa.init()
        if vecs.has('vel_bc'):
            self.ssa.set_boundary_conditions(vecs.bc_mask, vecs.vel_bc)

        melange_back_pressure = PISM.IceModelVec2S()
        melange_back_pressure.create(self.grid, "melange_back_pressure", PISM.WITHOUT_GHOSTS)
        melange_back_pressure.set_attrs("diagnostic",
                                        "melange back pressure fraction", "1", "")

        PISM.verbPrintf(2, self.grid.com, "* Solving the SSA stress balance ...\n")

        fast = False

        self.ssa.update(fast, melange_back_pressure)

        return self.ssa.velocity()
Exemplo n.º 2
0
    def write(self, filename):
        """Saves all of :attr:`modeldata`'s vecs (and the solution) to an
        output file."""
        grid = self.grid
        vecs = self.modeldata.vecs

        pio = PISM.PIO(grid.com, "netcdf3")
        pio.open(filename, PISM.PISM_READWRITE_MOVE)
        PISM.define_time(pio, grid.ctx().config().get_string("time_dimension_name"),
                         grid.ctx().config().get_string("calendar"),
                         grid.ctx().time().units_string(),
                         grid.ctx().unit_system())
        PISM.append_time(pio, grid.ctx().config().get_string("time_dimension_name"), 0.0)
        pio.close()

        # Save time & command line
        PISM.util.writeProvenance(filename)

        vecs.writeall(filename)

        vel_ssa = self.ssa.velocity()
        vel_ssa.write(filename)

        sys = self.grid.ctx().unit_system()

        velbar_mag = model.createCBarVec(self.grid)
        velbar_mag.set_to_magnitude(vel_ssa)
        velbar_mag.mask_by(vecs.thk, PISM.convert(sys, -0.01, "m/year", "m/second"))
        velbar_mag.write(filename)
Exemplo n.º 3
0
Arquivo: ssa.py Projeto: pism/pism
    def solve(self):
        """Solve the SSA by calling the underlying PISM :cpp:class:`SSA`'s
        :cpp:member:`update` method. Returns the solution vector (owned by
        self.ssa, but you should not need to know about ownership).

        """
        vecs = self.modeldata.vecs

        # make sure vecs is locked!
        self.ssa.init()

        melange_back_pressure = PISM.IceModelVec2S()
        melange_back_pressure.create(self.grid, "melange_back_pressure", PISM.WITHOUT_GHOSTS)
        melange_back_pressure.set_attrs("diagnostic",
                                        "melange back pressure fraction", "1", "")
        melange_back_pressure.set(0.0)

        PISM.verbPrintf(2, self.grid.com, "* Solving the SSA stress balance ...\n")

        full_update = True

        inputs                       = PISM.StressBalanceInputs()
        inputs.melange_back_pressure = melange_back_pressure
        inputs.geometry              = self.geometry
        inputs.enthalpy              = vecs.enthalpy
        inputs.basal_yield_stress    = vecs.tauc
        if vecs.has('vel_bc'):
            inputs.bc_mask   = vecs.bc_mask
            inputs.bc_values = vecs.vel_bc

        self.ssa.update(inputs, full_update)

        return self.ssa.velocity()
Exemplo n.º 4
0
def grounded_cell_fraction_test():

    # allocation
    grid = allocate_grid(ctx)

    ice_thickness, bed_topography, surface, mask, gl_mask, gl_mask_x, gl_mask_y, _ = allocate_storage(grid)

    bed_topography.set(0.0)

    # initialization
    sea_level = 500.0
    for L in [0.0, 0.25, 0.5, 0.75, 1.0]:
        init(mu, L, sea_level, ice_thickness, "box")

        compute_mask(sea_level, bed_topography, ice_thickness, mask, surface)

        # computation of gl_mask
        PISM.compute_grounded_cell_fraction(ice_density, ocean_density, sea_level,
                                            ice_thickness, bed_topography, mask, gl_mask,
                                            gl_mask_x, gl_mask_y)

        # inspection / comparison
        print("L = %f" % L)
        print_vec(mask)
        print_vec(gl_mask_x)
        print_vec(gl_mask_y)
        print_vec(gl_mask)
Exemplo n.º 5
0
  def report_riggs(self):
    grid = self.grid
    r=PISM.VerbPrintf(grid.com,verbosity=2)
    r.println("comparing to RIGGS data in %s ...\n",self.riggs_file); 

    riggsvars = [ "riggslat", "riggslon", "riggsmag", "riggsu", "riggsv"]
    (latdata,longdata,magdata,udata,vdata) = \
         (PISM.Timeseries(grid,varname,"count") for varname in riggsvars)
    riggsvars = [latdata, longdata, magdata, udata, vdata]

    for v in [magdata, udata, vdata]:
      v.set_units("m year-1", "")

    for v in riggsvars:
      v.read(self.riggs_file)

    length = latdata.length();

    vel_ssa = self.solver.solution();
    clat = self.latitude; clon = self.longitude; mask = self.solver.ice_mask;

    secpera=PISM.secpera
    with PISM.util.Access([clat,clon,mask,vel_ssa]):
      goodptcount = 0.0; ChiSqr = 0.0;    
      for k in xrange(length):
        (lat,lon,mag,u,v) = [v[k] for v in riggsvars]
        r.printlnv(4," RIGGS[%3d]: lat = %7.3f, lon = %7.3f, mag = %7.2f, u = %7.2f, v = %7.2f",
                          k,lat,lon,mag,u,v)
        origdlat = (-5.42445 - (-12.3325)) / 110.0;
        lowlat = -12.3325 - origdlat * 46.0;
        dlat = (-5.42445 - lowlat) / (float) (grid.My - 1);        
        lowlon = -5.26168;
        dlon = (3.72207 - lowlon) / (float) (grid.Mx - 1);
        cj = int( math.floor((lat - lowlat) / dlat) )
        ci = int( math.floor((lon - lowlon) / dlon) )
      
        if ((ci >= grid.xs) and (ci < grid.xs+grid.xm) and (cj >= grid.ys) and (cj < grid.ys+grid.ym)):
          vel = vel_ssa[ci,cj]
          cu = secpera * vel.u
          cv = secpera * vel.v
          cmag = math.sqrt(cu*cu + cv*cv)
          PISM.verbPrintf(4,PETSc.COMM_SELF,
                          " PISM%d[%3d]: lat = %7.3f, lon = %7.3f, mag = %7.2f, u = %7.2f, v = %7.2f\n",
                          grid.rank,k,clat[ci,cj],clon[ci,cj],cmag,cu,cv)
          if mask[ci,cj] == PISM.MASK_FLOATING:
            goodptcount += 1.0;
            ChiSqr += (u-cu)*(u-cu)+(v-cv)*(v-cv)
    # end with

    ChiSqr = ChiSqr / (30.0*30.0) # see page 48 of MacAyeal et al
    g_goodptcount = PISM.globalSum(goodptcount,grid.com)
    g_ChiSqr      = PISM.globalSum(ChiSqr, grid.com)
    r.printlnv( 4, """number of RIGGS data points = %d
number of RIGGS points in computed ice shelf region = %8.2f""", length , g_goodptcount);
    r.println("Chi^2 statistic for computed results compared to RIGGS is %10.3f",
                      g_ChiSqr * (156.0 / g_goodptcount))
Exemplo n.º 6
0
Arquivo: logging.py Projeto: pism/pism
def pause(message_in=None, message_out=None):
    """Prints a message and waits for a key press.

    :param message_in: Message to display before waiting.
    :param message_out: Message to display after waiting."""
    com = PISM.Context().com
    if not message_in is None:
        PISM.verbPrintf(1, com, message_in + "\n")
    _ = getkey()
    if not message_out is None:
        PISM.verbPrintf(1, com, message_out + "\n")
Exemplo n.º 7
0
def pism_pause(message_in=None, message_out=None):
    """Implements a ``siple`` pause callback appropriate for parallel runs."""
    import sys
    import os
    fd = sys.stdin.fileno()
    com = PISM.Context().com
    if os.isatty(fd):
        return siple.reporting.std_pause(message_in, message_out)
    if not message_in is None:
        PISM.verbPrintf(1, com, message_in + "\n")
    _ = sys.stdin.read(1)
    if not message_out is None:
        PISM.verbPrintf(1, com, message_out + "\n")
Exemplo n.º 8
0
Arquivo: util.py Projeto: pism/pism
def writeProvenance(outfile, message=None):
    """Saves the time and command line arguments (or the provided `message`) to
    the ``history`` attribute of the :file:`.nc` file `outfile`"""

    com = PISM.Context().com

    ds = PISM.PIO(com, "netcdf3", outfile, PISM.PISM_READWRITE)

    if message is None:
        message = PISM.timestamp(com) + ": " + PISM.args_string()
    ds.append_history(message)
    ds.put_att_text("PISM_GLOBAL", "source", "PISM " + PISM.PISM_Revision)

    ds.close()
Exemplo n.º 9
0
def create2dVelocityVec(grid, name="", desc="", intent="", ghost_type=PISM.WITH_GHOSTS, stencil_width=None):
    """Returns an :cpp:class:`IceModelVec2V` with attributes setup for horizontal velocity data.

    :param grid: The grid to associate with the vector.
    :param name: The intrinsic name to give the vector.

    :param ghost_type: One of ``PISM.WITH_GHOSTS`` or
                       ``PISM.WITHOUT_GHOSTS`` indicating if the vector
                       is ghosted.

    :param stencil_width: The size of the ghost stencil. Ignored if
                          ``ghost_type`` is ``PISM.WITHOUT_GHOSTS``. If
                          ``stencil_width`` is ``None`` and the vector
                          is ghosted, the grid's maximum stencil width
                          is used.

    """
    stencil_width = _stencil_width(grid, ghost_type, stencil_width)

    vel = PISM.IceModelVec2V()
    vel.create(grid, name, ghost_type, stencil_width)
    vel.set_attrs(intent, "%s%s" % ("X-component of the ", desc), "m s-1", "", 0)
    vel.set_attrs(intent, "%s%s" % ("Y-component of the ", desc), "m s-1", "", 1)
    vel.metadata(0).set_string("glaciological_units", "m year-1")
    vel.metadata(1).set_string("glaciological_units", "m year-1")
    vel.write_in_glaciological_units = True
    sys = grid.ctx().unit_system()
    huge_vel = PISM.convert(sys, 1e10, "m/year", "m/second")
    attrs = [("valid_min", -huge_vel), ("valid_max", huge_vel), ("_FillValue", 2 * huge_vel)]
    for a in attrs:
        for component in [0, 1]:
            vel.metadata(component).set_double(a[0], a[1])
    vel.set(2 * huge_vel)
    return vel
Exemplo n.º 10
0
  def updateYieldStress(self,mask,thickness,Hmelt,bmr,tillphi,tauc):
    config = PISM.global_config()
    till_pw_fraction = self.till_pw_fraction#config.get("till_pw_fraction")
    till_c_0 = self.till_c_0#config.get("till_c_0") * 1e3 # convert from kPa to Pa
    hmelt_max = self.hmelt_max#config.get("hmelt_max");

    rho_g = self.rho_g


    with PISM.util.Access(nocomm=[mask,tauc,thickness,Hmelt,bmr,tillphi]):
      mq = PISM.MaskQuery(mask)
      GHOSTS = self.grid.max_stencil_width;
      for (i,j) in self.grid.points_with_ghosts(nGhosts = GHOSTS):
        if mq.floating_ice(i,j):
          tauc[i,j] = 0
          continue

        H_ij = thickness[i,j]
        if H_ij == 0:
          tauc[i,j] = 1000.0e3;  #// large yield stress of 1000 kPa = 10 bar if no ice
        else: # grounded and there is some ice
          p_over = rho_g * H_ij
          p_w    = self.getBasalWaterPressure( H_ij,
                                         Hmelt[i,j],bmr[i,j],till_pw_fraction, 
                                         hmelt_max)
          N = p_over - p_w #  effective pressure on till
          tauc[i,j] = till_c_0 + N * math.tan((math.pi/180.0) * tillphi[i,j])
Exemplo n.º 11
0
Arquivo: util.py Projeto: pism/pism
def prepare_output(filename, append_time=True):
    "Create an output file and prepare it for writing."
    ctx = PISM.Context()
    output = PISM.PIO(ctx.com, ctx.config.get_string("output.format"),
                      filename, PISM.PISM_READWRITE_MOVE)
    PISM.define_time(output,
                     ctx.config.get_string("time.dimension_name"),
                     ctx.config.get_string("time.calendar"),
                     ctx.time.units_string(),
                     ctx.unit_system)
    if append_time:
        PISM.append_time(output,
                         ctx.config.get_string("time.dimension_name"),
                         ctx.time.current())

    return output
Exemplo n.º 12
0
def flowlaw_test():
    ctx = PISM.context_from_options(PISM.PETSc.COMM_WORLD, "flowlaw_test")
    EC = ctx.enthalpy_converter()
    ff = PISM.FlowLawFactory("sia_", ctx.config(), EC)
    law = ff.create()

    TpaC = [-30, -5, 0, 0]
    depth = 2000
    gs = 1e-3
    omega = [0.0, 0.0, 0.0, 0.005]
    sigma = [1e4, 5e4, 1e5, 1.5e5]

    p = EC.pressure(depth)
    Tm = EC.melting_temperature(p)

    print "flow law:   \"%s\"" % law.name()
    print "pressure = %9.3e Pa = (hydrostatic at depth %7.2f m)" % (p, depth)
    print "flowtable:"
    print "  (dev stress)   (abs temp) (liq frac) =   (flow)"

    for i in range(4):
        for j in range(4):
            T = Tm + TpaC[j]
            E = EC.enthalpy(T, omega[j], p)
            flowcoeff = law.flow(sigma[i], E, p, gs)
            print "    %10.2e   %10.3f  %9.3f = %10.6e" % (sigma[i], T, omega[j], flowcoeff)
Exemplo n.º 13
0
def add_disc_load(ice_thickness, radius, thickness):
    "Add a disc load with a given radius and thickness."
    grid = ice_thickness.grid()

    with PISM.vec.Access(nocomm=ice_thickness):
        for (i, j) in grid.points():
            r = PISM.radius(grid, i, j)
            if r <= disc_radius:
                ice_thickness[i, j] = disc_thickness
Exemplo n.º 14
0
 def __call__(self, message, verbosity):
     """Saves the message to our internal log string and writes the string out to the file."""
     if self.rank == 0 and PISM.getVerbosityLevel() >= verbosity:
         timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
         self.log = "%s%s: %s" % (self.log, timestamp, message)
         d = PISM.netCDF.Dataset(self.filename, 'a')
         d.__setattr__(self.attr, self.log)
         d.close()
     self.com.barrier()
Exemplo n.º 15
0
  def initPhysics(self):
    config = self.config
    self.basal = PISM.IceBasalResistancePlasticLaw(
           config.get("plastic_regularization") / PISM.secpera,
           config.get_flag("do_pseudo_plastic_till"),
           config.get("pseudo_plastic_q"),
           config.get("pseudo_plastic_uthreshold") / PISM.secpera);

    if PISM.optionsIsSet("-ssa_glen"):
      self.ice = PISM.CustomGlenIce(self.grid.com,"",config)
      B_schoof = 3.7e8;     # Pa s^{1/3}; hardness 
      self.ice.setHardness(B_schoof)
    else:
      self.ice =  PISM.GPBLDIce(self.grid.com, "", config)
    self.ice.setFromOptions()
    
    self.enthalpyconverter = PISM.EnthalpyConverter(config)
    if PISM.getVerbosityLevel() >3:
      self.enthalpyconverter.viewConstants(PETSc.Viewer.STDOUT())
Exemplo n.º 16
0
def standardBasalWaterVec(grid,name='bwat'):
  bwat = IceModelVec2S()
  bwat.create(grid,name,True,WIDE_STENCIL)
  bwat.set_attrs("model_state", "effective thickness of subglacial melt water",
                 "m", "")
  #// NB! Effective thickness of subglacial melt water *does* vary from 0 to hmelt_max meters only.
  bwat.set_attr("valid_min", 0.0)
  valid_max = PISM.global_config().get("hmelt_max")
  bwat.set_attr("valid_max", valid_max )
  return bwat
Exemplo n.º 17
0
  def setFromOptions(self):

    for o in PISM.OptionsGroup(self.grid.com,"","SSA options"):
      (ssa_method,wasSet) = PISM.optionsListWasSet(self.grid.com, "-ssa_method", 
                                    "Algorithm for computing the SSA solution",
                                    ["fem","fd","fem_f"], "fd")
      if wasSet: self.config.set_string("ssa_method",ssa_method);
      self.config.scalar_from_option("ssa_epsfd",  "epsilon_ssafd");
      self.config.scalar_from_option("ssa_maxi", "max_iterations_ssafd");
      self.config.scalar_from_option("ssa_rtol", "ssafd_relative_convergence");
Exemplo n.º 18
0
  def solve(self):
    if not self.ssa_init:
      pismVars = PISM.PISMVars()
      for var in [self.surface,self.thickness,self.bed,self.tauc,self.enthalpy,self.ice_mask]:
        pismVars.add(var)
        
      # The SSA instance will not keep a reference to pismVars; it only uses it to extract
      # its desired variables.  So it is safe to pass it pismVars and then let pismVars
      # go out of scope at the end of this method.
      self.ssa.init(pismVars)

      if not self.vel_bc is None:
        self.ssa.set_boundary_conditions(self.bc_mask,self.vel_bc)
      self.ssa_init = True
    
    PISM.verbPrintf(2,self.grid.com,"* Solving the SSA stress balance ...\n");
    fast = False;
    self.ssa.update(fast);
    self.vel_ssa = self.ssa.get_advective_2d_velocity()
Exemplo n.º 19
0
 def __call__(self, inverse_solver, count, data):
     """
     :param inverse_sovler: the solver (e.g. :class:`~InvSolver_Tikhonov`) we are listening to.
     :param count: the iteration number.
     :param data: dictionary of data related to the iteration.
     """
     method = inverse_solver.method
     if method != 'sd' and method != 'nlcg' and method != 'ign':
         if not self.didWarning:
             PISM.verbPrintf(1, PISM.Context().com, '\nWarning: unable to monitor adjoint for inverse method: %s\nOption -inv_monitor_adjoint ignored\n' % method)
         self.didWarning = True
         return
     fp = inverse_solver.forward_problem
     d = PISM.invert.sipletools.PISMLocalVector(data.d)
     r = PISM.invert.sipletools.PISMLocalVector(data.r)
     self.Td = fp.T(d, self.Td)
     self.TStarR = fp.TStar(r, out=self.TStarR)
     ip1 = fp.domainIP(d, self.TStarR)
     ip2 = fp.rangeIP(self.Td, r)
     logMessage("adjoint test: <Td,r>=%g <d,T^*r>=%g (percent error %g)", ip1, ip2, (abs(ip1 - ip2)) / max(abs(ip1), abs(ip2)))
Exemplo n.º 20
0
    def _initSSA(self):
        # Test J has a viscosity that is independent of velocity.  So we force a
        # constant viscosity by settting the strength_extension
        # thickness larger than the given ice thickness. (max = 770m).

        sys = self.grid.ctx().unit_system()
        nu0 = PISM.convert(sys, 30.0, "MPa year", "Pa s")
        H0 = 500.0                        # 500 m typical thickness

        ssa = self.ssa
        ssa.strength_extension.set_notional_strength(nu0 * H0)
        ssa.strength_extension.set_min_thickness(800.)
Exemplo n.º 21
0
  def report(self):
    uerr = 0.0; verr=0.0; relvecerr=0.0; accN=0.0 
    accArea=0.0; maxcComputed=0.0; vecErrAcc = 0.0;
    
    grid = self.grid
    area = grid.dx*grid.dy
  
    mask = self.solver.ice_mask;
    H = self.solver.thickness;
    azi=self.obsAzimuth;
    mag = self.obsMagnitude;
    acc = self.obsAccurate;
    vel_ssa = self.solver.solution();

    m = PISM.MaskQuery(mask)
    
    with PISM.util.Access([mask,H,azi,mag,acc,vel_ssa]):
      for (i,j) in grid.points():
        if m.ocean(i,j) and H[i,j] > 1.0:
          ccomputed = vel_ssa[i,j].magnitude()
          maxcComputed = max(maxcComputed,ccomputed)
          if( abs(acc[i,j]-1.0) < 0.1):
            accN += 1.0
            accArea += area
            uobs = mag[i,j] * math.sin((math.pi/180.0) * azi[i,j]);
            vobs = mag[i,j] * math.cos((math.pi/180.0) * azi[i,j]);
            Dv = abs(vobs-vel_ssa[i,j].v)
            Du = abs(uobs-vel_ssa[i,j].u)
            verr += Dv; uerr += Du
            relvecerr += (Dv*Dv+Du*Du) / (vobs*vobs+uobs*uobs)
            vecErrAcc += (Dv*Dv+Du*Du) * area

    gmaxcComputed = PISM.globalMax(maxcComputed,grid.com)
    gaccN         = PISM.globalSum(accN, grid.com)
    gaccArea      = PISM.globalSum(accArea, grid.com)
    gverr         = PISM.globalSum(verr, grid.com)
    guerr         = PISM.globalSum(uerr, grid.com)
    grelvecerr    = PISM.globalSum(relvecerr,grid.com)
    gvecErrAcc    = PISM.globalSum(vecErrAcc, grid.com)

    secpera = PISM.secpera
    r=PISM.VerbPrintf(self.grid.com,verbosity=2)
    r.println("maximum computed speed in ice shelf is %10.3f (m/a)", gmaxcComputed * secpera);
    r.println("ERRORS relative to observations of Ross Ice Shelf:");
    r.println("  [number of grid points in 'accurate observed area' = %d]", int(gaccN))
    r.println("  [area of 'accurate observed area' = %9.4f (km^2)]", gaccArea / 1e6)
    r.println("  following are average errors computed over 'accurate observed area':");
    r.println("  average error in x-comp of vel       = %9.3f (m/a)", (gverr * secpera) / gaccN);
    r.println("  average error in y-comp of vel       = %9.3f (m/a)",(guerr * secpera) / gaccN);
    r.println("  average relative error in vector vel = %9.5f", grelvecerr / gaccN)
    gvecErrAcc = secpera * math.sqrt(gvecErrAcc) / math.sqrt(gaccArea);
    r.println("  rms average error in vector vel      = %9.3f (m/a)\n", gvecErrAcc);
    
    if not self.riggs_file is None:
      self.report_riggs()
Exemplo n.º 22
0
  def setFromOptions(self):
    config = self.config
    
    # FIXME (DAM 4/28/11)
    # These options probably don't belong here.  Seems like IceBasalResistancePlasticLaw
    # should be able to set these for itself.  
    for o in PISM.OptionsGroup(title="Options for pseudo-plastic ice law"):
      # // use pseudo plastic instead of pure plastic; see iMbasal.cc
      config.flag_from_option("pseudo_plastic", "do_pseudo_plastic_till")

      # // power in denominator on pseudo_plastic_uthreshold; typical is q=0.25; q=0 is pure plastic
      config.scalar_from_option("pseudo_plastic_q", "pseudo_plastic_q")
      if PISM.optionsIsSet("-pseudo_plastic_q"):
        config.set_flag("do_pseudo_plastic_till", True)

      # // threshold; at this velocity tau_c is basal shear stress
      config.scalar_from_option("pseudo_plastic_uthreshold", "pseudo_plastic_uthreshold")
      if PISM.optionsIsSet("-pseudo_plastic_uthreshold"):
        config.set_flag("do_pseudo_plastic_till", True);

      # // controls regularization of plastic basal sliding law
      config.scalar_from_option("plastic_reg", "plastic_regularization")
Exemplo n.º 23
0
def grid_from_file_test():
    "Intiialize a grid from a file"
    grid = create_dummy_grid()

    enthalpy = PISM.model.createEnthalpyVec(grid)
    enthalpy.set(80e3)

    output_file = "test_grid_from_file.nc"
    pio = PISM.PIO(grid.com, "netcdf3")
    pio.open(output_file, PISM.PISM_READWRITE_MOVE)
    PISM.define_time(pio, grid.ctx().config().get_string("time_dimension_name"),
                     grid.ctx().config().get_string("calendar"),
                     grid.ctx().time().units_string(),
                     grid.ctx().unit_system())
    PISM.append_time(pio,
                     grid.ctx().config().get_string("time_dimension_name"),
                     grid.ctx().time().current())
    pio.close()

    enthalpy.write(output_file)

    grid2 = PISM.IceGrid.FromFile(grid.ctx(), output_file, "enthalpy", PISM.NOT_PERIODIC)
Exemplo n.º 24
0
def ssa_trivial_test():
    "Test the SSA solver using a trivial setup."

    context = PISM.Context()
    unit_system = context.unit_system

    L = 50.e3  # // 50km half-width
    H0 = 500  # // m
    dhdx = 0.005  # // pure number, slope of surface & bed
    nu0 = PISM.convert(unit_system, 30.0, "MPa year", "Pa s")
    tauc0 = 1.e4  # // 1kPa

    class TrivialSSARun(PISM.ssa.SSAExactTestCase):
        def _initGrid(self):
            self.grid = PISM.IceGrid.Shallow(PISM.Context().ctx, L, L, 0, 0,
                                             self.Mx, self.My, PISM.NONE)

        def _initPhysics(self):
            self.modeldata.setPhysics(context.enthalpy_converter)

        def _initSSACoefficients(self):
            self._allocStdSSACoefficients()
            self._allocateBCs()

            vecs = self.modeldata.vecs

            vecs.land_ice_thickness.set(H0)
            vecs.surface_altitude.set(H0)
            vecs.bedrock_altitude.set(0.0)
            vecs.tauc.set(tauc0)

            # zero Dirichler B.C. everywhere
            vecs.vel_bc.set(0.0)
            vecs.bc_mask.set(1.0)

        def _initSSA(self):
            # The following ensure that the strength extension is used everywhere
            se = self.ssa.strength_extension
            se.set_notional_strength(nu0 * H0)
            se.set_min_thickness(4000 * 10)

            # For the benefit of SSAFD on a non-periodic grid
            self.config.set_boolean("compute_surf_grad_inward_ssa", True)

        def exactSolution(self, i, j, x, y):
            return [0, 0]

    Mx = 11
    My = 11
    test_case = TrivialSSARun(Mx, My)
    test_case.run("ssa_trivial.nc")
Exemplo n.º 25
0
def pism_context_test():
    "Test creating and using a C++-level Context"

    com = PISM.PETSc.COMM_WORLD
    system = PISM.UnitSystem("")

    logger = PISM.Logger(com, 2)

    config = PISM.DefaultConfig(com, "pism_config", "-config", system)
    config.init_with_default(logger)

    EC = PISM.EnthalpyConverter(config)

    time = PISM.Time(config, "360_day", system)

    ctx = PISM.cpp.Context(com, system, config, EC, time, logger, "greenland")

    print ctx.com().Get_size()
    print ctx.config().get_double("standard_gravity")
    print ctx.enthalpy_converter().L(273.15)
    print ctx.time().current()
    print PISM.convert(ctx.unit_system(), 1, "km", "m")
    print ctx.prefix()
Exemplo n.º 26
0
    def __init__(self, ssarun, method):
        self.solver = None
        InvSSASolver.__init__(self, ssarun, method)

        self.target_misfit = PISM.optionsFlag("-inv_target_misfit",
                                              "m/year; desired root misfit for inversions", default=None)

        if self.target_misfit is None:
            raise RuntimeError("Missing required option -inv_target_misfit")

        # FIXME: m_vel_scale is not defined (what are the units?)
        self.target_misfit = self.target_misfit / m_vel_scale

        self.listeners = []
Exemplo n.º 27
0
def run(dt, restart=False):
    "Run the model for 1 time step, stop, save model state, restart, do 1 more step."

    grid = PISM.IceGrid.Shallow(ctx.ctx, Lx, Ly, 0, 0, N, N,
                                PISM.CELL_CORNER, PISM.NOT_PERIODIC)

    model = PISM.LingleClark(grid)

    ice_thickness, bed, bed_uplift, sea_level = allocate_storage(grid)
    grid.variables().add(ice_thickness)

    # start with a flat bed, no ice, and no uplift
    bed.set(0.0)
    bed_uplift.set(0.0)
    ice_thickness.set(0.0)
    sea_level.set(0.0)

    # initialize the model
    model.bootstrap(bed, bed_uplift, ice_thickness, sea_level)

    # add the disc load
    add_disc_load(ice_thickness, disc_radius, disc_thickness)

    # do 1 step
    model.step(ice_thickness, sea_level, dt)

    if restart:
        # save the model state
        filename = "lingle_clark_model_state.nc"
        try:
            PISM.util.prepare_output(filename)
            f = PISM.PIO(grid.com, "netcdf3", filename, PISM.PISM_READWRITE)
            model.write_model_state(f)
            f.close()

            # create a new model
            del model
            model = PISM.LingleClark(grid)

            # initialize
            PISM.PETSc.Options().setValue("-i", filename)
            options = PISM.process_input_options(grid.com, ctx.config)
            model.init(options, ice_thickness, sea_level)
        finally:
            os.remove(filename)

    # do 1 more step
    model.step(ice_thickness, sea_level, dt)

    return model
Exemplo n.º 28
0
def node_type_test():

    # allocation
    grid = allocate_grid(ctx)

    ice_thickness, mask = allocate_storage(grid)

    H = 1.0
    thickness_threshold = 0.5

    # initialization
    sea_level = 500.0

    init(H, ice_thickness)

    PISM.compute_node_types(ice_thickness, thickness_threshold, mask)

    # inspection / comparison
    plt.figure()
    spy_vec(ice_thickness, H)
    plt.figure()
    spy_vec(mask, 1.0)
    plt.show()
Exemplo n.º 29
0
  def __init__(self,Mx,My):
    self.grid = PISM.Context().newgrid()
    self.config = PISM.global_config()

    self.setFromOptions()
    
    self.initGrid(Mx,My)

    self.ice = None; self.basal = None; self.enthalpyconverter = None
    self.initPhysics()
    # FIXME: Check that the subclass did its job.

    self.solver = self._constructSSA()

    self.initSSACoefficients()
Exemplo n.º 30
0
def new_grounded_cell_fraction_test():

    # allocation
    grid = allocate_grid(ctx)

    ice_thickness, bed_topography, _, _, gl_mask, _, _, sea_level = allocate_storage(grid)

    # initialization
    bed_topography.set(0.0)
    sl = 500.0
    sea_level.set(sl)
    for L in [0.0, 0.25, 0.5, 0.75, 1.0]:
        init(mu, L, sl, ice_thickness, "box")

        # computation of gl_mask
        PISM.compute_grounded_cell_fraction(ice_density, ocean_density,
                                            sea_level,
                                            ice_thickness,
                                            bed_topography,
                                            gl_mask)

        # inspection / comparison
        print("L = %f" % L)
        print_vec(gl_mask)
Exemplo n.º 31
0
import PISM

com = PISM.PETSc.COMM_WORLD
sys = PISM.UnitSystem("")
log = PISM.StringLogger(com, 1)

pism_config = PISM.config_from_options(com, log, sys)

config = PISM.ConfigJSON(sys)
config.init_from_string("""
{
 "constants" : {"ice" : {}, "fresh_water" : {},  "sea_water" : {}},
 "bootstrapping" : {"defaults" : {}},
 "calving" : {"eigen_calving" : {}, "thickness_calving" : {}, "float_kill" : {}},
 "enthalpy_converter" : {},
 "flow_law" : {
   "gpbld" : {},
   "Hooke" : {},
   "isothermal_Glen": {},
   "Paterson_Budd" : {}},
 "grid" : {},
 "hydrology" : {},
 "fracture_density" : {},
 "stress_balance" : {
   "ssa" : {"strength_extension" : {}, "fd" : {"lateral_drag" : {}}},
   "sia" : {}
 },
 "time" : {},
 "geometry" : {"update" : {}, "part_grid" : {}},
 "climate_forcing" : {},
 "inverse" : {"design" : {}, "ssa" : {}, "tikhonov" : {}},
Exemplo n.º 32
0
def run(Mx, My, t_final, part_grid, C=1.0):
    "Test GeometryEvolution::step()"

    ctx = PISM.Context().ctx

    config = PISM.Context().config

    config.set_flag("geometry.part_grid.enabled", part_grid)

    grid = PISM.IceGrid_Shallow(ctx, 1, 1, 0, 0, Mx, My, PISM.CELL_CORNER,
                                PISM.NOT_PERIODIC)

    assert t_final <= 1.0

    L = min(grid.Lx(), grid.Ly())
    R_inner = 0.25 * L
    spreading_velocity = 0.7
    R_outer = R_inner + spreading_velocity * t_final

    geometry = PISM.Geometry(grid)

    v = PISM.IceModelVec2V(grid, "velocity", PISM.WITHOUT_GHOSTS)
    Q = PISM.IceModelVec2Stag(grid, "Q", PISM.WITHOUT_GHOSTS)
    H_bc_mask = PISM.IceModelVec2Int(grid, "H_bc_mask", PISM.WITHOUT_GHOSTS)

    ge = PISM.GeometryEvolution(grid)

    # grid info
    geometry.latitude.set(0.0)
    geometry.longitude.set(0.0)
    # environment
    geometry.bed_elevation.set(-10.0)
    geometry.sea_level_elevation.set(0.0)
    # set initial ice thickness
    disc(geometry.ice_thickness, 0, 0, 1, R_inner, R_inner)
    geometry.ice_area_specific_volume.set(0.0)

    geometry.ensure_consistency(0.0)

    set_velocity(spreading_velocity, v)
    disc(H_bc_mask, 0, 0, 1, R_inner, R_inner)

    profiling = ctx.profiling()
    profiling.start()

    t = 0.0
    j = 0
    profiling.stage_begin("ge")
    while t < t_final:
        cfl_data = PISM.max_timestep_cfl_2d(geometry.ice_thickness,
                                            geometry.cell_type, v)

        dt = cfl_data.dt_max.value() * C

        if t + dt > t_final:
            dt = t_final - t

        log.message(2, "{}, {}\n".format(t, dt))

        profiling.begin("step")
        ge.flow_step(geometry, dt, v, Q, H_bc_mask)
        profiling.end("step")

        profiling.begin("modify")
        ge.apply_flux_divergence(geometry)
        geometry.ensure_consistency(0.0)
        profiling.end("modify")

        t += dt
        j += 1
    profiling.stage_end("ge")

    profiling.report("profiling_%d_%d.py" % (Mx, My))

    return geometry
Exemplo n.º 33
0
def convert(value, u1, u2):
    "Convert value from units u1 to u2."
    unit_system = PISM.Context().unit_system
    return PISM.convert(unit_system, value, u1, u2)
Exemplo n.º 34
0
def create_grid_test():
    "Test the creation of the IceGrid object"
    grid1 = create_dummy_grid()

    grid2 = PISM.model.initGrid(PISM.Context(), 100e3, 100e3, 4000, 11, 11, 21,
                                PISM.NOT_PERIODIC)
Exemplo n.º 35
0
def options_test():
    "Test command-line option handling"
    ctx = PISM.Context()

    o = PISM.PETSc.Options()

    M = PISM.optionsInt("-M", "description", default=100)
    M = PISM.optionsInt("-M", "description", default=None)

    S = PISM.optionsString("-S", "description", default="string")
    S = PISM.optionsString("-S", "description", default=None)

    R = PISM.optionsReal("-R", "description", default=1.5)
    R = PISM.optionsReal("-R", "description", default=None)

    o.setValue("-B", "on")
    B = PISM.optionsFlag("-B", "description", default=False)
    B = PISM.optionsFlag("B", "description", default=False)
    B = PISM.optionsFlag("-B", "description", default=None)

    o.setValue("-no_C", "on")
    C = PISM.optionsFlag("C", "description", default=None)

    D = PISM.optionsFlag("D", "description", default=None)
    D = PISM.optionsFlag("D", "description", default=True)

    o.setValue("-no_D", "on")
    o.setValue("-D", "on")
    try:
        # should throw RuntimeError
        D = PISM.optionsFlag("D", "description", default=None)
        return False
    except RuntimeError:
        pass

    o.setValue("-IA", "1,2,3")
    IA = PISM.optionsIntArray("-IA", "description", default=[1, 2])
    IA = PISM.optionsIntArray("-IA", "description", default=None)
    IA2 = PISM.optionsIntArray("-IA2", "description", default=None)
    IA2 = PISM.optionsIntArray("-IA2", "description", default=[1, 2])

    o.setValue("-RA", "1,2,3")
    RA = PISM.optionsRealArray("-RA", "description", default=[2, 3])
    RA = PISM.optionsRealArray("-RA", "description", default=None)
    RA2 = PISM.optionsRealArray("-RA2", "description", default=[2, 3])
    RA2 = PISM.optionsRealArray("-RA2", "description", default=None)

    o.setValue("-SA", "1,2,3")
    SA = PISM.optionsStringArray("-SA", "description", default="one,two")
    SA = PISM.optionsStringArray("-SA", "description", default=None)
    SA2 = PISM.optionsStringArray("-SA2", "description", default="two,three")
    SA2 = PISM.optionsStringArray("-SA2", "description", default=None)

    M = PISM.optionsList("-L", "description", choices="one,two", default="one")
    M = PISM.optionsList("-L", "description", choices="one,two", default=None)
Exemplo n.º 36
0
 def _setFromOptions(self):
     """Initialize internal parameters based on command-line flags. Called from :meth:`PISM.ssa.SSARun.setup`."""
     self.is_regional = PISM.optionsFlag("-regional", "regional mode")
Exemplo n.º 37
0
def createTikhonovFunctionals(ssarun):
    """Returns a tuple ``(designFunctional,stateFunctional)`` of :cpp:class:`IP_Functional`'s
    for Tikhonov-based inversions.  The specific functionals are constructed on the basis of
    command-line parameters ``inv_state_func`` and ``inv_design_func``.

    :param ssarun: The instance of :class:`PISM.ssa.SSARun` that encapsulates the forward problem,
                   typically a :class:`SSATaucForwardRunFromFile`.
  """
    vecs = ssarun.modeldata.vecs
    grid = ssarun.grid

    useGroundedIceOnly = PISM.OptionBool("-inv_ssa_grounded_ice_tauc",
                                         "Computed norms for tau_c only on elements with all grounded ice.")

    misfit_type = grid.ctx().config().get_string("inverse.state_func")
    if misfit_type == "meansquare":
        stateFunctional = createMeanSquareMisfitFunctional(grid, vecs)
    elif misfit_type == "log_ratio":
        vel_ssa_observed = vecs.vel_ssa_observed
        scale = grid.ctx().config().get_double("inverse.log_ratio_scale")
        velocity_eps = grid.ctx().config().get_double("inverse.ssa.velocity_eps", "m/second")
        misfit_weight = None
        if vecs.has('vel_misfit_weight'):
            misfit_weight = vecs.vel_misfit_weight
        stateFunctional = PISM.IPLogRatioFunctional(grid, vel_ssa_observed, velocity_eps, misfit_weight)
        stateFunctional.normalize(scale)
    elif misfit_type == "log_relative":
        vel_ssa_observed = vecs.vel_ssa_observed
        velocity_scale = grid.ctx().config().get_double("inverse.ssa.velocity_scale", "m/second")
        velocity_eps = grid.ctx().config().get_double("inverse.ssa.velocity_eps", "m/second")
        misfit_weight = None
        if vecs.has('vel_misfit_weight'):
            misfit_weight = vecs.vel_misfit_weight
        stateFunctional = PISM.IPLogRelativeFunctional(grid, vel_ssa_observed, velocity_eps, misfit_weight)
        stateFunctional.normalize(velocity_scale)
    else:
        raise RuntimeError("Unknown inv_state_func '%s'; unable to construct solver.", misfit_type)

    design_functional = grid.ctx().config().get_string("inverse.design.func")
    if design_functional == "sobolevH1":
        designFunctional = createHilbertDesignFunctional(grid, vecs, useGroundedIceOnly)
    elif design_functional == "tv":
        area = 4 * grid.Lx() * grid.Ly()
        velocity_scale = grid.ctx().config().get_double("inverse.ssa.velocity_scale", "m/second")
        length_scale = grid.ctx().config().get_double("inverse.ssa.length_scale")
        lebesgue_exponent = grid.ctx().config().get_double("inverse.ssa.tv_exponent")
        cTV = 1 / area
        cTV *= (length_scale) ** (lebesgue_exponent)

        zeta_fixed_mask = None
        if vecs.has('zeta_fixed_mask'):
            zeta_fixed_mask = vecs.zeta_fixed_mask

        strain_rate_eps = PISM.optionsReal("-inv_ssa_tv_eps",
                                           "regularization constant for 'total variation' functional", default=None)
        if strain_rate_eps is None:
            schoofLen = grid.ctx().config().get_double("flow_law.Schoof_regularizing_length", "m")
            strain_rate_eps = 1 / schoofLen

        designFunctional = PISM.IPTotalVariationFunctional2S(grid, cTV, lebesgue_exponent, strain_rate_eps, zeta_fixed_mask)
    else:
        raise Exception("Unknown inv_design_func '%s'; unable to construct solver." % design_functional)

    return (designFunctional, stateFunctional)
Exemplo n.º 38
0
    def _initSSACoefficients(self):
        """Reads SSA coefficients from the input file. Called from :meth:`PISM.ssa.SSARun.setup`."""
        self._allocStdSSACoefficients()

        # Read PISM SSA related state variables
        #
        # Hmmm.  A lot of code duplication with SSAFromInputFile._initSSACoefficients.

        vecs = self.modeldata.vecs
        thickness = vecs.land_ice_thickness
        bed = vecs.bedrock_altitude
        enthalpy = vecs.enthalpy
        mask = vecs.mask
        surface = vecs.surface_altitude
        sea_level = vecs.sea_level

        sea_level.set(0.0)

        # Read in the PISM state variables that are used directly in the SSA solver
        for v in [thickness, bed, enthalpy]:
            v.regrid(self.input_filename, True)

        # variables mask and surface are computed from the geometry previously read

        gc = PISM.GeometryCalculator(self.config)
        gc.compute(sea_level, bed, thickness, mask, surface)

        grid = self.grid
        config = self.modeldata.config

        # Compute yield stress from PISM state variables
        # (basal melt rate, tillphi, and basal water height) if they are available

        file_has_inputs = (PISM.util.fileHasVariable(self.input_filename, 'bmelt') and
                           PISM.util.fileHasVariable(self.input_filename, 'tillwat') and
                           PISM.util.fileHasVariable(self.input_filename, 'tillphi'))

        if file_has_inputs:
            bmr = PISM.model.createBasalMeltRateVec(grid)
            tillphi = PISM.model.createTillPhiVec(grid)
            tillwat = PISM.model.createBasalWaterVec(grid)
            for v in [bmr, tillphi, tillwat]:
                v.regrid(self.input_filename, True)
                vecs.add(v)

            # hydrology models use cell areas:
            cell_area = PISM.model.createCellAreaVec(grid)
            if PISM.util.fileHasVariable(self.input_filename, 'cell_area'):
                cell_area.regrid(self.input_filename, True)
            vecs.add(cell_area)

            # The SIA model might need the age field.
            if self.config.get_boolean("age.enabled"):
                vecs.age.regrid(self.input_filename, True)

            hydrology_model = config.get_string("hydrology.model")
            if hydrology_model == "null":
                subglacial_hydrology = PISM.NullTransportHydrology(grid)
            elif hydrology_model == "routing":
                subglacial_hydrology = PISM.RoutingHydrology(grid)
            elif hydrology_model == "distributed":
                subglacial_hydrology = PISM.DistributedHydrology(grid)

            if self.is_regional:
                yieldstress = PISM.RegionalDefaultYieldStress(self.modeldata.grid, subglacial_hydrology)
            else:
                yieldstress = PISM.MohrCoulombYieldStress(self.modeldata.grid, subglacial_hydrology)

            # make sure vecs is locked!
            subglacial_hydrology.init()
            yieldstress.init()

            yieldstress.basal_material_yield_stress(vecs.tauc)
        elif PISM.util.fileHasVariable(self.input_filename, 'tauc'):
            vecs.tauc.regrid(self.input_filename, critical=True)

        if PISM.util.fileHasVariable(self.input_filename, 'ssa_driving_stress_x'):
            vecs.add(PISM.model.createDrivingStressXVec(self.grid))
            vecs.ssa_driving_stress_x.regrid(self.input_filename, critical=True)

        if PISM.util.fileHasVariable(self.input_filename, 'ssa_driving_stress_y'):
            vecs.add(PISM.model.createDrivingStressYVec(self.grid))
            vecs.ssa_driving_stress_y.regrid(self.input_filename, critical=True)

        # read in the fractional floatation mask
        vecs.add(PISM.model.createGroundingLineMask(self.grid))
        vecs.gl_mask.regrid(self.input_filename, critical=False, default_value=0.0)  # set to zero if not found

        if self.is_regional:
            vecs.add(PISM.model.createNoModelMaskVec(self.grid), 'no_model_mask')
            vecs.no_model_mask.regrid(self.input_filename, True)
            vecs.add(vecs.surface_altitude, 'usurfstore')

        if self.config.get_boolean('stress_balance.ssa.dirichlet_bc'):
            vecs.add(PISM.model.create2dVelocityVec(self.grid, name='_ssa_bc', desc='SSA velocity boundary condition', intent='intent'), "vel_ssa_bc")
            has_u_ssa_bc = PISM.util.fileHasVariable(self.input_filename, 'u_ssa_bc')
            has_v_ssa_bc = PISM.util.fileHasVariable(self.input_filename, 'v_ssa_bc')
            if (not has_u_ssa_bc) or (not has_v_ssa_bc):
                PISM.verbPrintf(2, self.grid.com, "Input file '%s' missing Dirichlet boundary data u/v_ssa_bc; using zero default instead." % self.input_filename)
                vecs.vel_ssa_bc.set(0.)
            else:
                vecs.vel_ssa_bc.regrid(self.input_filename, True)

            if self.is_regional:
                vecs.add(vecs.no_model_mask, 'bc_mask')
            else:
                vecs.add(PISM.model.createBCMaskVec(self.grid), 'bc_mask')
                bc_mask_name = vecs.bc_mask.metadata().get_string("short_name")
                if PISM.util.fileHasVariable(self.input_filename, bc_mask_name):
                    vecs.bc_mask.regrid(self.input_filename, True)
                else:
                    PISM.verbPrintf(2, self.grid.com, "Input file '%s' missing Dirichlet location mask '%s'.  Default to no Dirichlet locations." % (self.input_filename, bc_mask_name))
                    vecs.bc_mask.set(0)

        if PISM.util.fileHasVariable(self.inv_data_filename, 'vel_misfit_weight'):
            vecs.add(PISM.model.createVelocityMisfitWeightVec(self.grid))
            vecs.vel_misfit_weight.regrid(self.inv_data_filename, True)
Exemplo n.º 39
0
#!/usr/bin/env python3

"Test the 'Given' bed deformation model."

import PISM
from PISM.testing import shallow_grid, create_forcing
import os
import numpy as np

from unittest import TestCase

ctx = PISM.Context()
ctx.log.set_threshold(1)

# set run duration so that all forcing used here spans the duration of the run
time = ctx.time
time.set_start(0.5)
time.set_end(1)


class BeddefGiven(TestCase):
    def setUp(self):

        self.geometry_filename = "beddef_given_input.nc"
        self.filename = "beddef_given.nc"
        self.ref_filename = "beddef_given_reference.nc"

        self.grid = shallow_grid(Mx=3, My=3)

        # Create time-dependent topography changes
        create_forcing(self.grid,
Exemplo n.º 40
0
def fileHasVariable(filename, varname):
    """Returns ``True`` if the :file:`.nc` file `filename` contains an variable named `varname`."""

    return PISM.PIO(PISM.Context().com, "netcdf3", filename, PISM.PISM_READONLY).inq_var(varname)
Exemplo n.º 41
0
    def setUp(self):
        "Prepare an input file with an interesting time-dependent field."
        self.filename = "input.nc"
        self.empty = "empty.nc"
        self.one_record = "one_record.nc"
        self.no_time = "no_time.nc"
        self.no_bounds = "no_time_bounds.nc"
        self.time_order = "time_order.nc"

        self.period = 1

        M = 3
        self.grid = PISM.IceGrid.Shallow(ctx.ctx, 1, 1, 0, 0, M, M,
                                         PISM.CELL_CORNER, PISM.NOT_PERIODIC)

        v = PISM.IceModelVec2S(self.grid, "v", PISM.WITHOUT_GHOSTS)

        units = "days since 1-1-1"
        N = 12
        dt = 30.0  # days (floating point)
        t = numpy.r_[0:N] * dt
        self.tb = numpy.r_[0:N + 1] * dt
        self.f = numpy.sin(2.0 * numpy.pi * t / (N * dt))

        def write_data(filename, use_bounds=True, forward=True):
            bounds = PISM.TimeBoundsMetadata("time_bounds", "time",
                                             ctx.unit_system)
            bounds.set_string("units", units)

            output = PISM.util.prepare_output(filename, append_time=False)
            output.write_attribute("time", "units", units)

            if use_bounds:
                output.write_attribute("time", "bounds", "time_bounds")

            if forward:
                order = range(N)
            else:
                order = range(N - 1, -1, -1)

            for k in order:
                PISM.append_time(output, "time", self.tb[k + 1])

                if use_bounds:
                    PISM.write_time_bounds(output, bounds, k,
                                           (self.tb[k], self.tb[k + 1]))

                v.set(self.f[k])
                v.write(output)

        # regular forcing file
        write_data(self.filename, use_bounds=True)

        # file without time bounds
        write_data(self.no_bounds, use_bounds=False)

        # file with invalid time order
        write_data(self.time_order, forward=False)

        # empty file
        PISM.util.prepare_output(self.empty)

        # file with one record
        output = PISM.util.prepare_output(self.one_record)
        v.set(self.f[-1])
        v.write(output)

        # file without a time dimension
        v.set(self.f[-1])
        v.set_time_independent(True)
        v.dump(self.no_time)
Exemplo n.º 42
0
#!/usr/bin/env python3
"""
Tests of PISM's surface models and modifiers.
"""

import PISM
from PISM.testing import *
import sys
import os
import numpy as np
from unittest import TestCase, SkipTest

from PISM.util import convert

# set run duration to 1 second so that all forcing used here spans the duration of the run
time = PISM.Context().time
time.set_start(0)
time.set_end(1)

config = PISM.Context().config

seconds_per_year = 365 * 86400
# ensure that this is the correct year length
config.set_string("time.calendar", "365_day")

log = PISM.Context().log
# silence models' initialization messages
log.set_threshold(1)

options = PISM.PETSc.Options()
Exemplo n.º 43
0
 def exactSolution(self, i, j, x, y):
     p = PISM.exactI(m_schoof, x, y)
     return [p.u, p.v]
Exemplo n.º 44
0
def surface_simple(grid):
    return PISM.SurfaceSimple(grid, PISM.AtmosphereUniform(grid))
Exemplo n.º 45
0
def modelvecs_test():
    "Test the ModelVecs class"

    grid = create_dummy_grid()

    mask = PISM.model.createIceMaskVec(grid)
    mask.set(PISM.MASK_GROUNDED)

    modeldata = PISM.model.ModelData(grid)
    vecs = modeldata.vecs

    vecs.add(mask, "ice_mask", writing=True)

    # use the default name, no writing
    vecs.add(PISM.model.createIceThicknessVec(grid))

    try:
        vecs.add(mask, "ice_mask")
        return False
    except RuntimeError:
        # should fail: mask was added already
        pass

    # get a field:
    print "get() method: ice mask: ", vecs.get(
        "ice_mask").metadata().get_string("long_name")

    print "dot notation: ice mask: ", vecs.ice_mask.metadata().get_string(
        "long_name")

    try:
        vecs.invalid
        return False
    except AttributeError:
        # should fail
        pass

    try:
        vecs.get("invalid")
        return False
    except RuntimeError:
        # should fail
        pass

    # test __repr__
    print vecs

    # test has()
    print "Has thickness?", vecs.has("thickness")

    # test markForWriting
    vecs.markForWriting("ice_mask")

    vecs.markForWriting(mask)

    vecs.markForWriting("thk")

    # test write()
    output_file = "test_ModelVecs.nc"
    pio = PISM.PIO(grid.com, "netcdf3")
    pio.open(output_file, PISM.PISM_READWRITE_MOVE)
    PISM.define_time(pio,
                     grid.ctx().config().get_string("time_dimension_name"),
                     grid.ctx().config().get_string("calendar"),
                     grid.ctx().time().units_string(),
                     grid.ctx().unit_system())
    PISM.append_time(pio,
                     grid.ctx().config().get_string("time_dimension_name"),
                     grid.ctx().time().current())
    pio.close()

    vecs.write(output_file)

    # test writeall()
    vecs.writeall(output_file)
Exemplo n.º 46
0
 def setUp(self):
     self.grid = shallow_grid()
     self.output_filename = filename("surface_simple_output_")
     self.atmosphere = PISM.AtmosphereUniform(self.grid)
     self.geometry = PISM.Geometry(self.grid)
Exemplo n.º 47
0
def printing_test():
    "Test verbPrintf"
    ctx = PISM.Context()
    PISM.verbPrintf(1, ctx.com, "hello %s!\n", "world")
Exemplo n.º 48
0
 def setUp(self):
     self.grid = shallow_grid()
     self.geometry = PISM.Geometry(self.grid)
     self.output_filename = filename("surface_eismint_output_")
Exemplo n.º 49
0
#!/usr/bin/env python
"""Solves equation (16) of BuelerLingleBrown to obtain the steady
state viscous plate deflection corresponding to a given disc load.

Used as a verification (and regression) test for LingleClarkSerial::bootstrap().
"""

import PISM
import pylab as plt
import numpy as np
from PISM.util import convert

config = PISM.Context().config
log = PISM.Context().log

# constants
standard_gravity = config.get_double("constants.standard_gravity")
ice_density = config.get_double("constants.ice.density")
mantle_density = config.get_double("bed_deformation.mantle_density")
mantle_viscosity = config.get_double("bed_deformation.mantle_viscosity")
lithosphere_flexural_rigidity = config.get_double(
    "bed_deformation.lithosphere_flexural_rigidity")

# disc load parameters
disc_radius = convert(1000, "km", "m")
disc_thickness = 1000.0  # meters
# domain size
Lx = 2 * disc_radius
# time to use for the comparison
T = convert(1e6, "years", "second")
t_final = convert(20000, "years", "second")
Exemplo n.º 50
0
 def setUp(self):
     self.grid = shallow_grid()
     self.geometry = PISM.Geometry(self.grid)
     self.output_filename = filename("surface_init_output_")
     self.model = surface_simple(self.grid)
Exemplo n.º 51
0
    threshold = threshold * threshold
    with PISM.vec.Access(comm=weight, nocomm=[vel_ssa, mask]):
        weight.set(0.)
        grounded = PISM.MASK_GROUNDED
        for (i, j) in grid.points():
            u = vel_ssa[i, j].u
            v = vel_ssa[i, j].v
            if mask[i, j] == grounded:
                if u * u + v * v > threshold:
                    weight[i, j] = 1
    return weight


# The main code for a run follows:
if __name__ == '__main__':
    context = PISM.Context()
    com = context.com

    PISM.set_abort_on_sigint(True)

    PISM.verbosityLevelFromOptions()
    PISM.verbPrintf(2, PISM.Context().com, "SSA forward model.\n")
    if PISM.OptionBool("-version", "stop after printing PISM version"):
        sys.exit(0)

    usage = \
        """  %s -i IN.nc -Mx number -My number [-o file.nc]
  or (at python prompt)
    run %s -i IN.nc -Mx number -My number [-o file.nc]
  where:
    -i      IN.nc is input file in NetCDF format: contains PISM-written model state
Exemplo n.º 52
0
 def setUp(self):
     self.grid = shallow_grid()
     self.geometry = PISM.Geometry(self.grid)
Exemplo n.º 53
0
import PISM
import numpy as np
""" Test mass transport code using a circularly-symmetric setup in which
a disc expands uniformly in all directions. Given mass conservation,
the thickness of this disc outside of the fixed circular area (the
thickness Dirichlet B.C. area) is inversely proportional to the
distance from the center. Here we use this 'exact solution' to test
the symmetry of the produced ice thickness and linear convergence
towards the exact solution."""

log = PISM.Context().log


def disc(thickness, x0, y0, H0, R_inner, R_outer):
    """Set ice thickness to H0 within the disc centered at (x0,y0) of
    radius R_inner, C/R in an annulus R_inner < r <= R_outer and 0
    elsewhere.

    """

    grid = thickness.grid()

    R_inner_2 = R_inner**2
    R_outer_2 = R_outer**2

    C = H0 * R_inner

    with PISM.vec.Access(nocomm=thickness):
        for (i, j) in grid.points():
            x = grid.x(i)
            y = grid.y(j)
Exemplo n.º 54
0
    def prepare_climate_forcing(self, grid, filename):

        aSMB = PISM.IceModelVec2S(grid, "climatic_mass_balance_anomaly",
                                  PISM.WITHOUT_GHOSTS)
        aSMB.set_attrs("climate_forcing", "SMB anomaly", "kg m-2 s-1",
                       "kg m-2 s-1", "", 0)

        dSMBdz = PISM.IceModelVec2S(grid, "climatic_mass_balance_gradient",
                                    PISM.WITHOUT_GHOSTS)
        dSMBdz.set_attrs("climate_forcing", "SMB gradient", "kg m-2 s-1 m-1",
                         "kg m-2 s-1 m-1", "", 0)

        aT = PISM.IceModelVec2S(grid, "ice_surface_temp_anomaly",
                                PISM.WITHOUT_GHOSTS)
        aT.set_attrs("climate_forcing", "temperature anomaly", "Kelvin",
                     "Kelvin", "", 0)

        dTdz = PISM.IceModelVec2S(grid, "ice_surface_temp_gradient",
                                  PISM.WITHOUT_GHOSTS)
        dTdz.set_attrs("climate_forcing", "surface temperature gradient",
                       "K m-1", "K m-1", "", 0)

        out = PISM.util.prepare_output(filename, append_time=False)

        bounds = PISM.VariableMetadata("time_bounds", self.ctx.unit_system)

        PISM.define_time_bounds(bounds, "time", "nv", out, PISM.PISM_DOUBLE)

        SMB_anomaly = 1.0
        T_anomaly = 1.0
        SMB_gradient = 1.0
        T_gradient = 1.0

        # monthly steps
        dt = (365 * 86400) / 12.0

        for j in range(12):

            t = self.ctx.time.current() + j * dt

            PISM.append_time(out, self.ctx.config, t)

            PISM.write_time_bounds(out, bounds, j, [t, t + dt])

            aSMB.set(t * SMB_anomaly)

            dSMBdz.set(t * SMB_gradient)

            aT.set(t * T_anomaly)

            dTdz.set(t * T_gradient)

            for v in [aSMB, dSMBdz, aT, dTdz]:
                v.write(out)

        out.redef()
        out.write_attribute("time", "bounds", "time_bounds")
        out.write_attribute("time", "units", "seconds since 1-1-1")

        out.close()
Exemplo n.º 55
0
def vertical_extrapolation_during_regridding_test():
    "Test extrapolation in the vertical direction"
    # create a grid with 11 levels, 1000m thick
    ctx = PISM.Context()
    params = PISM.GridParameters(ctx.config)
    params.Lx = 1e5
    params.Ly = 1e5
    params.Mx = 3
    params.My = 3
    params.Mz = 11
    params.Lz = 1000
    params.registration = PISM.CELL_CORNER
    params.periodicity = PISM.NOT_PERIODIC
    params.ownership_ranges_from_options(ctx.size)

    z = np.linspace(0, params.Lz, params.Mz)
    params.z[:] = z

    grid = PISM.IceGrid(ctx.ctx, params)

    # create an IceModelVec that uses this grid
    v = PISM.IceModelVec3(grid, "test", PISM.WITHOUT_GHOSTS, grid.z())
    v.set(0.0)

    # set a column
    with PISM.vec.Access(nocomm=[v]):
        v.set_column(1, 1, z)

    # save to a file
    file_name = filename("regridding")
    try:
        v.dump(file_name)

        # create a taller grid (to 2000m):
        params.Lz = 2000
        params.Mz = 41
        z_tall = np.linspace(0, params.Lz, params.Mz)
        params.z[:] = z_tall

        tall_grid = PISM.IceGrid(ctx.ctx, params)

        # create an IceModelVec that uses this grid
        v_tall = PISM.IceModelVec3(tall_grid, "test", PISM.WITHOUT_GHOSTS,
                                   tall_grid.z())

        # Try regridding without extrapolation. This should fail.
        try:
            ctx.ctx.log().disable()
            v_tall.regrid(file_name, PISM.CRITICAL)
            ctx.ctx.log().enable()
            raise AssertionError(
                "Should not be able to regrid without extrapolation")
        except RuntimeError as e:
            pass

        # allow extrapolation during regridding
        ctx.config.set_flag("grid.allow_extrapolation", True)

        # regrid from test.nc
        ctx.ctx.log().disable()
        v_tall.regrid(file_name, PISM.CRITICAL)
        ctx.ctx.log().enable()

        # get a column
        with PISM.vec.Access(nocomm=[v_tall]):
            column = np.array(v_tall.get_column(1, 1))

        # compute the desired result
        desired = np.r_[np.linspace(0, 1000, 21), np.zeros(20) + 1000]

        # compare
        np.testing.assert_almost_equal(column, desired)
    finally:
        os.remove(file_name)
Exemplo n.º 56
0
def create_dummy_grid():
    "Create a dummy grid"
    ctx = PISM.Context()
    params = PISM.GridParameters(ctx.config)
    params.ownership_ranges_from_options(ctx.size)
    return PISM.IceGrid(ctx.ctx, params)
Exemplo n.º 57
0
def pism_ends_with_test():
    "Test PISM.ends_with()"
    assert PISM.ends_with("foo.nc", ".nc") == True
    assert PISM.ends_with("foo.nc and more text", ".nc") == False
    assert PISM.ends_with("short_string", "longer_suffix") == False
Exemplo n.º 58
0
def context_test():
    "Test creating a new PISM context"
    ctx = PISM.Context()
    config = ctx.config
    us = ctx.unit_system
    EC = ctx.enthalpy_converter
Exemplo n.º 59
0
help = \
    """
SSA_TESTCFBC
  Testing program for PISM's implementations of the SSA.
  Does a time-independent calculation.  Does not run IceModel or a derived
  class thereof. Uses the van der Veen flow-line shelf geometry. Also may be
  used in a PISM software (regression) test.
"""

usage = \
    """
usage of SSA_TEST_CFBC:
  run ssa_test_cfbc -Mx <number> -My <number>
"""

context = PISM.Context()
unit_system = context.unit_system

H0 = 600.  # meters
V0 = PISM.convert(unit_system, 300, "m/year", "m/second")
C = 2.45e-18  # "typical constant ice parameter"
T = 400  # time used to compute the calving front location

Q0 = V0 * H0
Hc1 = 4. * C / Q0
Hc2 = 1. / (H0**4)


def H_exact(x):
    return (Hc1 * x + Hc2)**(-1 / 4.)
Exemplo n.º 60
0
                edge = ((j == 0) or
                        (j == grid.My() - 1)) or ((i == 0) or
                                                  (i == grid.Mx() - 1))
                if edge:
                    bc_mask[i, j] = 1
                    vel_bc[i, j].u = p.u
                    vel_bc[i, j].v = p.v

    def exactSolution(self, i, j, x, y):
        p = PISM.exactI(m_schoof, x, y)
        return [p.u, p.v]


# The main code for a run follows:
if __name__ == '__main__':
    context = PISM.Context()

    PISM.set_abort_on_sigint(True)

    Mx = PISM.optionsInt("-Mx",
                         "Number of grid points in x-direction",
                         default=11)
    My = PISM.optionsInt("-My",
                         "Number of grid points in y-direction",
                         default=61)
    output_file = PISM.optionsString("-o", "output file", default="testi.nc")

    tc = testi(Mx, My)
    tc.run(output_file)