def ferret_putdata(self, line): ''' Line-level magic to put data to ferret. In [31]: import numpy as np ....: b = {} ....: b['name']='myvar' ....: b['name']='myvar' ....: x=np.linspace(-np.pi*4, np.pi*4, 500) ....: b['data']=np.sin(x)/x ....: b.keys() Out[31]: ['data', 'name'] In [32]: %ferret_putdata --axis_pos (1,0,2,3,4,5) b ....: Message: b is now available in ferret as myvar ''' args = parse_argstring(self.ferret_putdata, line) ferretvariable = unicode_to_str(args.code[0]) if args.axis_pos: axis_pos_variable = eval(args.axis_pos) else: axis_pos_variable = None pyferret.putdata(self.shell.user_ns[ferretvariable], axis_pos=axis_pos_variable) publish_display_data('ferretMagic.ferret', {'text/html': '<pre style="background-color:#F2F5A9; border-radius: 4px 4px 4px 4px; font-size: smaller">' + 'Message: ' + ferretvariable + ' is now available in ferret as ' + self.shell.user_ns[ferretvariable]['name'] + '</pre>' })
def ferret_putdata(self, line): ''' Line-level magic to put data to ferret. In [31]: import numpy as np ....: b = {} ....: b['name']='myvar' ....: b['name']='myvar' ....: x=np.linspace(-np.pi*4, np.pi*4, 500) ....: b['data']=np.sin(x)/x ....: b.keys() Out[31]: ['data', 'name'] In [32]: %ferret_putdata --axis_pos (1,0,2,3,4,5) b ....: Message: b is now available in ferret as myvar ''' args = parse_argstring(self.ferret_putdata, line) ferretvariable = unicode_to_str(args.code[0]) if args.axis_pos: axis_pos_variable = eval(args.axis_pos) else: axis_pos_variable = None pyferret.putdata(self.shell.user_ns[ferretvariable], axis_pos=axis_pos_variable) publish_display_data({'text/html': '<pre style="background-color:#F2F5A9; border-radius: 4px 4px 4px 4px; font-size: smaller">' + 'Message: ' + ferretvariable + ' is now available in ferret as ' + self.shell.user_ns[ferretvariable]['name'] + '</pre>' })
def _assigninferret(self, varname, dsetname): ''' (overrides FerVar._assigninferret) Assign the data in this FerPyVar as a PyVar in Ferret. varname (string): name for the PyVar in Ferret dsetname (string): associated the PyVar with this dataset in Ferret Raises a ValueError is a problem occurs. Note: Ferret will rearrange axes, if necessary, so that any longitude axis is the first axis, any latitude axis is the second axis, any level axis is the third axis, any time axis is the fourth axis or the sixth axis for a second time axis. The data will, of course, also be appropriately structured to remain consistent with the axes. ''' if not isinstance(varname, str): raise ValueError('varname must be a string') if not varname: raise ValueError('varname is empty') if not isinstance(dsetname, str): raise ValueError('dsetname must be a string') # TODO: fix libpyferret so PyVar's can be created without a dataset # (uses Ferret's dataset '0') if not dsetname: raise ValueError( 'a FerPyVar cannot be associated with an anonymous dataset at this time' ) axtypes = [] axcoords = [] axunits = [] axnames = [] for axis in self._datagrid.getaxes(): axtypes.append(axis.getaxtype()) axcoords.append(axis.getcoords()) axunits.append(axis.getunit()) axnames.append(axis.getname()) datadict = { 'name': varname, 'dset': dsetname, 'data': self._dataarray, 'missing_value': self._missingvalue, 'data_unit': self._dataunit, 'axis_types': axtypes, 'axis_coords': axcoords, 'axis_units': axunits, 'axis_names': axnames, } if self._title: datadict['title'] = self._title try: pyferret.putdata(datadict) except Exception as ex: raise ValueError(str(ex)) self._varname = varname self._dsetname = dsetname self._definition = self.fername()
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