Beispiel #1
0
 def read_raw(self):
     rawfile = fd.DumbCheckpoint("X_end", mode=fd.FILE_READ)
     rawfile.load(self.X)
     rawfile.close()
     rawfile = fd.DumbCheckpoint("U_end", mode=fd.FILE_READ)
     rawfile.load(self.U)
     rawfile.close()
Beispiel #2
0
 def write_raw(self):
     rawfile = fd.DumbCheckpoint("X_end", mode=fd.FILE_CREATE)
     rawfile.store(self.X)
     rawfile.close()
     rawfile = fd.DumbCheckpoint("U_end", mode=fd.FILE_CREATE)
     rawfile.store(self.U)
     rawfile.close()
Beispiel #3
0
def write_checkpoint(states, dirpath, filename, fieldname="solution"):
    """Write checkpoint for restarting and/or post-processing.
    
    A solution is stored for each state in states.
    
    Restarting requires states filling the time discretization stencil.
    
    If a checkpoint already exists for a state's time, then no new
    checkpoint is written for that state.
    """
    checkpointer = fe.DumbCheckpoint(basename=str(dirpath) + "/" + filename,
                                     mode=fe.FILE_UPDATE)

    stored_times, stored_indices = checkpointer.get_timesteps()

    for state in states:

        time = state["time"].__float__()

        if time in stored_times:

            continue

        else:

            solution = state["solution"]

            checkpointer.set_timestep(t=time, idx=state["index"])

            print("Writing checkpoint to {}".format(
                checkpointer.h5file.filename))

            checkpointer.store(solution, name=fieldname)
Beispiel #4
0
def getCheckPointVars(checkFile, varNames, Q, t=None):
    """ Read a variable from a firedrake checkpoint file

    Parameters
    ----------
    checkFile : str
        checkfile name sans .h5
    varNames : str or list of str
        Names of variables to extract
    Q : firedrake function space
        firedrake function space can be a vector space, V, but not mixed
    Returns
    -------
    myVars: dict
        {'myVar':}
    """
    # Ensure a list since a single str is allowed
    if type(varNames) is not list:
        varNames = [varNames]
    # open checkpoint
    myVars = {}
    if not os.path.exists(f'{checkFile}.h5'):
        myerror(f'getCheckPointVar: file {checkFile}.h5 does not exist')
    with firedrake.DumbCheckpoint(checkFile, mode=firedrake.FILE_READ) as chk:
        if t is not None:
            print(t)
            chk.set_timestep(t)
        for varName in varNames:
            myVar = firedrake.Function(Q, name=varName)
            chk.load(myVar, name=varName)
            myVars[varName] = myVar
    return myVars
Beispiel #5
0
 def load(self, vec, filename="control"):
     """
     Load a vector from a file.
     DumbCheckpoint requires that the mesh, FunctionSpace and parallel
     decomposition are identical between store and load.
     """
     with fd.DumbCheckpoint(filename, mode=fd.FILE_READ) as chk:
         chk.load(vec.fun, name=filename)
Beispiel #6
0
    def store(self, vec, filename="control"):
        """
        Store the vector to a file to be reused in a later computation.
        DumbCheckpoint requires that the mesh, FunctionSpace and parallel
        decomposition are identical between store and load.

        """
        with fd.DumbCheckpoint(filename, mode=fd.FILE_CREATE) as chk:
            chk.store(vec.fun, name=filename)
Beispiel #7
0
def saveInversionResult(inversionParams, modelResults, solverBeta,
                        solverTheta, A, theta, beta, grounded, floating,
                        h, s, zb, uObs):
    """Save results to a firedrake dumbcheckpoint file
    """
    outFile = \
        f'{inversionParams["inversionResult"]}.deg{inversionParams["degree"]}'
    # Names used in checkpoint file - use dict for yaml dump
    varNames = {'uInv': 'uInv', 'betaInv': 'betaInv', 'AInv': 'AInv',
                'groundedInv': 'groundedInv', 'floatingInv': 'floatingInv',
                'hInv': 'hInv', 'sInv': 'sInv', 'zbInv': 'zbInv',
                'uObsInv': 'uObsInv', 'thetaInv': 'thetaInv'}
    # variables to constrain inversion
    myVars = {'AInv': A, 'groundedInv': grounded, 'floatingInv': floating,
              'hInv': h, 'sInv': s, 'zbInv': zb, 'uObsInv': uObs}
    # Write results to check point file
    with firedrake.DumbCheckpoint(outFile, mode=firedrake.FILE_CREATE) as chk:
        # Beta solution
        if solverBeta is not None:  # Save inversion
            chk.store(solverBeta.parameter, name=varNames['betaInv'])
        else:  # Save value used
            chk.store(beta, name=varNames['betaInv'])
        # Theta solution
        if solverTheta is not None:  # Save param and final state if solved
            chk.store(solverTheta.parameter, name=varNames['thetaInv'])
            chk.store(solverTheta.state, name=varNames['uInv'])
        else:  # Save theta used throughout model and final result
            chk.store(theta, name=varNames['thetaInv'])
            chk.store(solverBeta.state, name=varNames['uInv'])  # Save beta v
        # Save other variables
        for myVar in myVars:
            chk.store(myVars[myVar], name=myVar)
    # Save end time
    modelResults['end_time'] = datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
    # dump inputs and summary data to yaml file
    outParams = f'{inversionParams["inversionResult"]}.' \
                f'deg{inversionParams["degree"]}.yaml'
    with open(outParams, 'w') as fpYaml:
        myDicts = {'inversionParams': inversionParams,
                   'modelResults': modelResults, 'varNames': varNames}
        yaml.dump(myDicts, fpYaml)
Beispiel #8
0
def read_checkpoint(states, dirpath, filename, fieldname="solution"):

    checkpointer = fe.DumbCheckpoint(basename=str(dirpath) + "/" + filename,
                                     mode=fe.FILE_READ)

    stored_times, stored_indices = checkpointer.get_timesteps()

    for state in states:

        time = state["time"].__float__()

        assert (time in stored_times)

        solution = state["solution"]

        checkpointer.set_timestep(t=time, idx=state["index"])

        print("Reading checkpoint from {}".format(
            checkpointer.h5file.filename))

        checkpointer.load(solution, name=fieldname)

    return states
Beispiel #9
0
def setupOutputs(forwardParams, inversionParams, meltParams, check=True):
    ''' Make output dir and dump forward and inversionParams
    '''
    if not os.path.exists(forwardParams['forwardResultDir']):
        os.mkdir(forwardParams['forwardResultDir'])
    inputsFile = f'{forwardParams["forwardResultDir"]}/' \
                 f'{forwardParams["forwardResult"]}.inputs.yaml'
    chkFile = f'{forwardParams["forwardResultDir"]}/' \
              f'{forwardParams["forwardResult"]}.history'
    summaryFile = f'{forwardParams["forwardResultDir"]}/' \
                  f'{forwardParams["forwardResult"]}.summary.yaml'
    # Abort if noOverwrite and all files exist
    noOverwrite = forwardParams['noOverwrite']
    for myFile in [inputsFile, f'{chkFile}.h5', summaryFile]:
        noOverwrite = noOverwrite and os.path.exists(myFile)
        print(myFile, noOverwrite)
    if noOverwrite:
        myerror(f'\nProducts exist for: {inputsFile}\nand noOverwrite set\n')
    # Continue with new or overwrite
    print(f'Writing inputs to: {inputsFile}')
    #
    with open(inputsFile, 'w') as fpYaml:
        myDicts = {
            'forwardParams': forwardParams,
            'inversionParams': inversionParams,
            'meltParams': meltParams
        }
        print
        yaml.dump(myDicts, fpYaml)
    # open check point file
    if check:
        if forwardParams['restart']:
            mode = firedrake.FILE_UPDATE
        else:
            mode = firedrake.FILE_CREATE
        return firedrake.DumbCheckpoint(chkFile, mode=mode)
    return None
Beispiel #10
0
Lx, Ly = 640e3, 80e3
ny = 20
nx = int(Lx / Ly) * ny
coarse_mesh = firedrake.RectangleMesh(nx, ny, Lx, Ly)
mesh_hierarchy = firedrake.MeshHierarchy(coarse_mesh, args.level)
mesh = mesh_hierarchy[args.level]

Q = firedrake.FunctionSpace(mesh, family='CG', degree=1)
V = firedrake.VectorFunctionSpace(mesh, family='CG', degree=1)

h = firedrake.Function(Q)
u = firedrake.Function(V)

input_name = os.path.splitext(args.input)[0]
with firedrake.DumbCheckpoint(input_name, mode=firedrake.FILE_READ) as chk:
    timesteps, indices = chk.get_timesteps()
    chk.set_timestep(timesteps[-1], idx=indices[-1])

    chk.load(h, name='h')
    chk.load(u, name='u')

fig, axes = icepack.plot.subplots(nrows=2,
                                  sharex=True,
                                  sharey=True,
                                  figsize=(6.4, 2.8))

axes[0].get_xaxis().set_visible(False)
for ax in axes:
    ax.set_xlim(0, 640e3)
    ax.set_ylim(0, 80e3)
Beispiel #11
0
parser.add_argument('--undamaged')
parser.add_argument('--damaged')
parser.add_argument('--output')
args = parser.parse_args()

def colorbar(figure, axes, mappable, *args, **kwargs):
    divider = make_axes_locatable(axes)
    cax = divider.append_axes('right', size='5%', pad=0.05)
    return figure.colorbar(mappable, *args, cax=cax, **kwargs)

mesh = firedrake.Mesh(args.mesh)
Q = firedrake.FunctionSpace(mesh, family='CG', degree=2)
V = firedrake.VectorFunctionSpace(mesh, family='CG', degree=2)
Δ = firedrake.FunctionSpace(mesh, family='DG', degree=1)

with firedrake.DumbCheckpoint(args.undamaged, mode=firedrake.FILE_READ) as chk:
    h_undamaged = firedrake.Function(Q)
    u_undamaged = firedrake.Function(V)
    chk.load(h_undamaged, name='h')
    chk.load(u_undamaged, name='u')

with firedrake.DumbCheckpoint(args.damaged, mode=firedrake.FILE_READ) as chk:
    h_damaged = firedrake.Function(Q)
    u_damaged = firedrake.Function(V)
    D = firedrake.Function(Δ)
    chk.load(h_damaged, name='h')
    chk.load(u_damaged, name='u')
    chk.load(D, name='D')

δh = firedrake.interpolate(h_damaged - h_undamaged, Q)
Beispiel #12
0
import icepack.plot


def colorbar(figure, axes, mappable, *args, **kwargs):
    divider = make_axes_locatable(axes)
    cax = divider.append_axes('right', size='5%', pad=0.05)
    return figure.colorbar(mappable, *args, cax=cax, **kwargs)


mesh = firedrake.Mesh('ice-shelf.msh')
Q = firedrake.FunctionSpace(mesh, family='CG', degree=2)
V = firedrake.VectorFunctionSpace(mesh, family='CG', degree=2)
Δ = firedrake.FunctionSpace(mesh, family='DG', degree=1)

filename = 'steady-state-undamaged'
with firedrake.DumbCheckpoint(filename, mode=firedrake.FILE_READ) as chk:
    h_undamaged = firedrake.Function(Q)
    u_undamaged = firedrake.Function(V)
    chk.load(h_undamaged, name='h')
    chk.load(u_undamaged, name='u')

filename = 'steady-state-damaged'
with firedrake.DumbCheckpoint(filename, mode=firedrake.FILE_READ) as chk:
    h_damaged = firedrake.Function(Q)
    u_damaged = firedrake.Function(V)
    D = firedrake.Function(Δ)
    chk.load(h_damaged, name='h')
    chk.load(u_damaged, name='u')
    chk.load(D, name='D')

δh = firedrake.interpolate(h_damaged - h_undamaged, Q)
Beispiel #13
0
# Create the mass balance
ela = 300.
max_a = 0.  # alternative: 0.5
da_ds = 0.  # alternative: 0.5 / 1000


def mass_balance(s, max_a, da_ds, ela):
    return min_value((s - ela) * da_ds, max_a)


# Pick a timestep, a duration, and run the simulation
dt = args.timestep
num_timesteps = args.num_steps

for step in tqdm.trange(num_timesteps):
    a = interpolate(mass_balance(s, ela, max_a, da_ds), Q)
    h = solver.prognostic_solve(dt, thickness=h, accumulation=a, velocity=u)

    h.interpolate(max_value(h, 0))
    s = interpolate(h + b, Q)

    u = solver.diagnostic_solve(velocity=u, thickness=h, surface=s, fluidity=A)

# Write out the results to a file
output_name = os.path.splitext(args.output)[0]
with firedrake.DumbCheckpoint(output_name, mode=firedrake.FILE_CREATE) as chk:
    chk.store(b, name='bed')
    chk.store(h, name='thickness')
    chk.store(h0, name='thickness-initial')
    chk.store(u, name='velocity')
Beispiel #14
0
# We run up in powers of 2 until we have plenty of observations per cell (on average)

# In[4]:

signal_to_noise = 20
U = u_true.dat.data_ro[:]
u_range = U.max() - U.min()
σ = firedrake.Constant(u_range / signal_to_noise)

methods = ['point-cloud', 'nearest', 'linear', 'clough-tocher', 'gaussian']

min_power_of_2 = 2
max_power_of_2 = 20

# We will dump our results to a checkpoint
chk = firedrake.DumbCheckpoint("poisson-inverse-conductivity-posterior-consistency-chk", mode=firedrake.FILE_CREATE)
np_file = open('poisson-inverse-conductivity-posterior-consistency-chk.npy', 'wb')

for i in range(min_power_of_2, max_power_of_2+1):

    print(f'i = {i}')

    # Setup Plot
    ukw = {'vmin': 0.0, 'vmax': +0.2}
    kw = {'vmin': -4, 'vmax': +4, 'shading': 'gouraud'}
    title_fontsize = 20
    text_fontsize = 20
    fig, axes = plt.subplots(ncols=3, nrows=1+len(methods), sharex=True, sharey=True, figsize=(20,30), dpi=200)
    plt.suptitle('Estimating Log-Conductivity $q$ \n    where $k = k_0e^q$ and $-\\nabla \\cdot k \\nabla u = f$ for known $f$', fontsize=title_fontsize)
    for ax in axes.ravel():
        ax.set_aspect('equal')