示例#1
0
    def halt(self):
        # Close pyferret
        pyferret.stop()

        print('Removing temporary directory: ', tmpdir)
        shutil.rmtree(tmpdir)

        super(myArbiter, self).halt()
示例#2
0
def regrid_once_primitive(var, ref_var, axis,
                          verbose=False, prerun=None, transform='@ave'):
    ''' A generic function that regrids a variable without the dependence of
    geodat.nc.Variable

    Args:
        var (dict) : arguments for num2fer
                 Required keys: data,coords,dimunits
        ref_var (dict)  :  arguments for num2fer.
                       This supplies the grid for regridding
                       Required keys: coords,dimunits
        axis (str) : the axis for regridding e.g. 'X'/'Y'/'XY'/"YX"
        verbose (bool) : whether to print progress (default: False)
        prerun (a list of str) : commands to be run at the start (default: None)
        transform (str): "@ave" (Conserve area average),
                     "@lin" (Linear interpolation),...see Ferret doc
    Returns:
        dict
    '''
    if not PYFERRET_INSTALLED:
        raise _IMPORT_PYFERRET_ERROR

    pyferret.start(quiet=True, journal=verbose,
                   verify=False, server=True)
    # commands to run before regridding
    if prerun is not None:
        if type(prerun) is str:
            pyferret.run(prerun)
        elif type(prerun) is list:
            for s in prerun:
                if type(s) is str:
                    pyferret.run(prerun)
                else:
                    raise Exception("prerun has to be either a string or "+\
                                    "a list of string")
        else:
            raise Exception("prerun has to be either a string or a list of "+\
                            "string")

    assert isinstance(axis, str)
    axis = axis.upper()
    # Make sure axis is a string denoting X or Y axis
    #if axis not in ['X', 'Y', 'XY', 'YX']:
    #    raise Exception("Currently axis can only be X/Y/XY")

    # Construct the source data read by pyferret.putdata
    source_fer = num2fer(**var)
    source_fer["name"] = "source"

    # Fill in unnecessary input for Ferret
    if "data" not in ref_var:
        ref_var['data'] = numpy.zeros((1,)*len(ref_var['coords']))

    # Construct the destination data read by pyferret.putdata
    dest_fer = num2fer(**ref_var)
    dest_fer["name"] = "dest"

    if verbose:
        print source_fer
        print dest_fer
    pyferret.putdata(source_fer, axis_pos=source_fer['axis_pos'])
    if verbose:
        print "Put source variable"
        pyferret.run('show grid source')
    pyferret.putdata(dest_fer, axis_pos=dest_fer['axis_pos'])
    if verbose:
        print "Put destination variable"
        pyferret.run('show grid dest')

    pyfer_command = 'let result = source[g'+axis.lower()+'=dest'+transform+']'
    pyferret.run(pyfer_command)
    if verbose:
        print "Regridded in FERRET"
        pyferret.run('show grid result')

    # Get results
    result_ref = pyferret.getdata('result')
    if verbose: print "Get data from FERRET"
    # Convert from ferret data structure to geodat.nc.Variable
    tmp_result = fer2num(result_ref)
    if 'varname' in var:
        tmp_result['varname'] = var['varname']
    tmp_caxes = [geodat.units.assign_caxis(dimunit)
                 for dimunit in tmp_result['dimunits']]
    var_caxes = [geodat.units.assign_caxis(dimunit)
                 for dimunit in var['dimunits']]
    # Preserve dimension order (Ferret reverts the order)
    neworder = [tmp_caxes.index(cax)
                for cax in var_caxes]
    # Change the dimension order of the result to match with the input
    tmp_result['coords'] = [tmp_result['coords'][iax] for iax in neworder]
    tmp_result['dimunits'] = [tmp_result['dimunits'][iax] for iax in neworder]
    if 'dimnames' in tmp_result:
        tmp_result['dimnames'] = [tmp_result['dimnames'][iax]
                                  for iax in neworder]
    tmp_result['data'] = tmp_result['data'].transpose(neworder).astype(
        var['data'].dtype)
    # Return the input var with the data and dimensions replaced by
    # the regridded ones
    var.update(tmp_result)
    result = var
    status = pyferret.stop()
    if verbose:
        if status:
            print "PyFerret stopped."
        else:
            print "PyFerret failed to stop."
    return result