Esempio n. 1
0
def argusToFiredrakeMesh(meshFile, savegmsh=False):
    """Convert an argus mesh to firedrake
    Parameters
    ----------
    meshFile : string
        File name of an Argus mesh export
    savegmsh : bool
        Save gmsh file
    Return
    ----------
    mesh : firedrake mesh
    opts : dict
    """
    myMesh = m.argusMesh(meshFile)  # Input the mesh
    # Quick Check that file is a value argus mesh
    if '.exp' not in meshFile:
        m.myerror(f'Invalid mesh file [{meshFile}]: missing .exp')
    # create unique ide to avoid multiple jobs overwriting
    myId = f'.{uuid.uuid4().hex[:8]}.msh'
    gmshFile = meshFile.replace(".exp", myId)
    myMesh.toGmsh(gmshFile)  # Save in gmsh format
    mesh = firedrake.Mesh(gmshFile)
    # delete gmsh file
    if not savegmsh:
        os.remove(gmshFile)
    else:
        os.rename(gmshFile, gmshFile.replace(myId, '.msh'))
    opts = readOpts(meshFile)
    # return mesh
    return mesh, opts
Esempio n. 2
0
def parseInversionParams(parser, defaults):
    '''
    Parse model params with the following precedence:
    1) Set at command line,
    2) Set in a parameter file,
    3) Default value.
    '''
    args = parser.parse_args()
    # params that are remapped an negated
    reMap = {'noViscosity': 'solveViscosity', 'noBeta': 'solveBeta'}
    # Read file
    inversionParams = mf.readModelParams(args.params, key='inversionParams')
    for arg in vars(args):
        # If value input through command line, override existing.
        argVal = getattr(args, arg)
        if arg in reMap:
            arg = reMap[arg]
            argVal = not argVal
        if argVal is not None:
            inversionParams[arg] = argVal
    for key in defaults:
        if key not in inversionParams:
            inversionParams[key] = defaults[key]
    #
    inversionParams['inversionResult'] = inversionParams['inversionResult'][0]
    # Handle conflicts
    if inversionParams['maxSteps'] <= 0 or inversionParams['rtol'] <= 0.:
        myerror(f'maxSteps ({args.maxSteps}) and rtol {args.rtol} must be > 0')
    if inversionParams['degree'] == 1 and inversionParams['initWithDeg1']:
        myerror('degree=1 not compatible with initWithDeg1')
    return inversionParams
Esempio n. 3
0
 def readGmshHeader(self, gmshFile):
     ''' read gmsh header, return pointer to start of nodes'''
     try:
         fpGmsh = open(gmshFile, 'r')
     except Exception:
         myerror(f'error opening gmsh input file {gmshFile}')
     for line in fpGmsh:
         if '$Nodes' in line:
             return fpGmsh
     myerror(f'Reached end of {gmshFile} with no $Nodes found')
Esempio n. 4
0
 def gmshHeader(self, gmshFile):
     ''' Open gmsh file and write header'''
     # open file
     try:
         fpGmsh = open(gmshFile, 'w')
     except Exception:
         myerror(f'error opening gmsh output file {gmshFile}')
     # Header info
     print('$MeshFormat', file=fpGmsh)
     print('2.2 0 8', file=fpGmsh)
     print('$EndMeshFormat', file=fpGmsh)
     return fpGmsh
Esempio n. 5
0
def getModelVelocity(baseName, Q, V, minSigma=5, maxSigma=100):
    """Read in a tiff velocity data set and return
    firedrake interpolate functions.

    Parameters
    ----------
    baseName : str
        baseName should be of the form pattern.*.abc or pattern
        The wildcard (*) will be filled with the suffixes (vx, vy.)
        e.g.,pattern.vx.abc.tif, pattern.vy.abc.tif.
    Q : firedrake function space
        function space
    V : firedrake vector space
        vector space
    Returns
    -------
    uObs firedrake interp function on V
        velocity (m/yr)
    speed firedrake interp function on Q
        speed in (m)
    sigmaX firedrake interp function on Q
        vx error (m)
    sigmaY firedrake interp function on Q
        vy error (m)
    """
    # suffixes for products used
    suffixes = ['vx', 'vy', 'ex', 'ey']
    rasters = {}
    # prep baseName - baseName.*.xyz.tif or baseName.*
    if '*' not in baseName:
        baseName += '.*'
    if '.tif' not in baseName:
        baseName += '.tif'
    # read data
    for suffix in suffixes:
        myBand = baseName.replace('*', suffix)
        if not os.path.exists(myBand):
            myerror(f'Velocity/error file - {myBand} - does not exist')
        rasters[suffix] = rasterio.open(myBand, 'r')
    # Firedrake interpolators
    uObs = icepack.interpolate((rasters['vx'], rasters['vy']), V)
    # force error to be at least 1 to avoid 0 or negatives.
    sigmaX = icepack.interpolate(rasters['ex'], Q)
    sigmaX = icepack.interpolate(firedrake.max_value(sigmaX, minSigma), Q)
    sigmaX = icepack.interpolate(firedrake.min_value(sigmaX, maxSigma), Q)
    sigmaY = icepack.interpolate(rasters['ey'], Q)
    sigmaY = icepack.interpolate(firedrake.max_value(sigmaY, minSigma), Q)
    sigmaY = icepack.interpolate(firedrake.min_value(sigmaY, maxSigma), Q)
    speed = icepack.interpolate(firedrake.sqrt(inner(uObs, uObs)), Q)
    # return results
    return uObs, speed, sigmaX, sigmaY
Esempio n. 6
0
def readModelParams(paramsFile, key=None):
    """Parse a model params dict from a yaml file. File can either have a
    single unnamed dict:
    x: abc
    y: xyz
    or several:
    key1:
        x: abc
        y: xyc
    key2:
        var1: 1
        var2: 5
    In the former case no key is need. In the latter case, if a specific dict
    is required, it should be specified using "key", otherwise a dict of dicts
    will be returned.
    Parameters
    ----------
    paramsFile : str
        yaml file with desired model params
    key: str [Optional]
        key to select which dict to return.

    Returns
    -------
    dict
        dict with model params with 'params' added as file it was read from.
    """
    if paramsFile is None:
        return {}
    try:
        with open(paramsFile) as fp:
            modelParams = yaml.load(fp, Loader=yaml.FullLoader)
            if key is not None:
                if key in modelParams:
                    modelParams = modelParams[key]
            # Force to use name of file actually being read
            modelParams['params'] = paramsFile
    except Exception:
        myerror(f'Could not open params file: {paramsFile}')
    return modelParams
Esempio n. 7
0
 def readGmshElements(self, fpGmsh):
     ''' read elements from a gmsh file '''
     try:
         print(f'{fpGmsh.readline()}')
         nNewElements = int(fpGmsh.readline().strip())
     except Exception:
         myerror('readGmshElements: cannot parse nLines')
     #
     elIndex, elRead = len(self.elIndex), 0
     for line in fpGmsh:
         elData = [eval(x) for x in line.split()]
         self.elements.append(elData[5:])
         self.elementType.append(elData[1])
         self.tag.append(elData[3])
         self.group.append(elData[4])
         elIndex += 1  # Increment el index and append
         self.elIndex.append(elIndex)
         elRead += 1  # Increment el counter
         if elRead == nNewElements:
             print(f'Read {elRead} elements')
             self.nElements += elRead
             break
     if elRead != nNewElements:
         myerror(f'readGmshElements: expected {nNewElements} nodes read '
                 f'{elRead}')
     if '$EndElements' not in fpGmsh.readline():
         myerror(f'readGmshNodes: expected $EndElements')
Esempio n. 8
0
 def readGmshNodes(self, fpGmsh):
     ''' read nodes from a gmsh file '''
     try:
         nNewNodes = int(fpGmsh.readline().strip())
     except Exception:
         myerror('readGmshNodes: cannot parse nLines')
     #
     nodeIndex, nodesRead = len(self.nodeIndex), 0
     for line in fpGmsh:
         nodeData = [eval(x) for x in line.split()]
         self.nodes.append(nodeData[1:3])
         self.nodeValues.append(nodeData[3])
         nodeIndex += 1  # Increment node index and append
         self.nodeIndex.append(nodeIndex)
         nodesRead += 1  # Increment node counter
         if nodesRead == nNewNodes:
             print(f'Read {nodesRead} nodes')
             self.nNodes += nodesRead
             break
     self.nodes = np.array(self.nodes)
     print(self.nodes.shape)
     if nodesRead != nNewNodes:
         myerror(f'readGmshNodes: expected {nNewNodes} nodes read '
                 f'{nodesRead}')
     if '$EndNodes' not in fpGmsh.readline():
         myerror(f'readGmshNodes: expected $EendNodes')
Esempio n. 9
0
def readOpts(meshFile):
    """Read and opts file if there is one
    Parameters
    ----------
    meshFile : str
        opts file name
    Return
    ----------
    opts: dict
        opts data
    """
    optsFile = meshFile.replace('.exp', '.yaml')
    if not os.path.exists(optsFile):
        return {}
    with open(optsFile, 'r') as fp:
        try:
            opts = yaml.load(fp, Loader=yaml.FullLoader)
        except Exception:
            m.myerror(f'Error reading opts file: {optsFile}')
    if 'opts' in opts:
        opts = opts['opts']
    return opts