How to use cfunits - 7 common examples

To help you get started, we’ve selected a few cfunits examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github atmos-python / atmos / atmos / solve.py View on Github external
def __new__(cls, name, parents, dct):
        if dct['_equation_module'] is not None:
            # Update the class docstring
            if '__doc__' in dct.keys():
                dct['__doc__'] = _fill_doc(
                    dct['__doc__'], dct['_equation_module'],
                    dct['default_assumptions'])
            dct['_ref_units'] = {}
            for quantity in dct['_equation_module'].quantities.keys():
                dct['_ref_units'][quantity] = \
                    cfunits.Units(dct['_equation_module'].quantities[
                        quantity]['units'])
            assumptions = set([])
            for f in inspect.getmembers(equations):
                try:
                    assumptions.update(f[1].assumptions)
                except AttributeError:
                    pass
            dct['all_assumptions'] = tuple(assumptions)

        # we need to call type.__new__ to complete the initialization
        instance = super(SolverMeta, cls).__new__(cls, name, parents, dct)
        return instance
github NCPP / ocgis / src / ocgis / api / request / nc.py View on Github external
def conform_units_to(self,value):
        if value is not None:
            ## import the cfunits package and attempt to construct a units object.
            ## if this is okay, save the units string
            from cfunits import Units
            dest = Units(value)
            ## the units of the source data need to be specified or available
            ## in the metadata.
            try:
                src = self.units or self._get_units_from_metadata_()
                src = Units(src)
            except KeyError:
                exc = NoUnitsError(message='Units could not be read from source metadata. The "units" keyword argument may be needed.')
                ocgis_lh(exc=exc)
            ## units must be equivalent.
            try:
                assert(src.equivalent(dest))
            except AssertionError:
                ocgis_lh(exc=ValueError('The units specified in "conform_units_to" ("{0}") are not equivalent to the source units "{1}".'.format(dest.format(names=True),src.format(names=True))))
            self._conform_units_to = value
        else:
            self._conform_units_to = None
github NCPP / ocgis / src / ocgis / api / request / nc.py View on Github external
def conform_units_to(self,value):
        if value is not None:
            ## import the cfunits package and attempt to construct a units object.
            ## if this is okay, save the units string
            from cfunits import Units
            dest = Units(value)
            ## the units of the source data need to be specified or available
            ## in the metadata.
            try:
                src = self.units or self._get_units_from_metadata_()
                src = Units(src)
            except KeyError:
                exc = NoUnitsError(message='Units could not be read from source metadata. The "units" keyword argument may be needed.')
                ocgis_lh(exc=exc)
            ## units must be equivalent.
            try:
                assert(src.equivalent(dest))
            except AssertionError:
                ocgis_lh(exc=ValueError('The units specified in "conform_units_to" ("{0}") are not equivalent to the source units "{1}".'.format(dest.format(names=True),src.format(names=True))))
            self._conform_units_to = value
        else:
            self._conform_units_to = None
github atmos-python / atmos / atmos / solve.py View on Github external
self.units = {}
        remove_kwargs = []
        for kwarg in kwargs:
            m = _unit_kwarg_prog.match(kwarg)
            if m is not None:
                # select whichever group is not None
                var = m.group(1) or m.group(2)
                self._ensure_quantities(var)
                if var in self.units:
                    raise ValueError(
                        'units for {} specified multiple times'.format(var))
                unit_str = kwargs[kwarg]
                remove_kwargs.append(kwarg)
                if not isinstance(unit_str, string_types):
                    raise TypeError('units must be strings')
                self.units[var] = cfunits.Units(unit_str)
        for kwarg in remove_kwargs:
            kwargs.pop(kwarg)
        # make sure the remaining variables are quantities
        self._ensure_quantities(*kwargs.keys())
        # convert quantities to reference units
        for kwarg in kwargs:
            if (kwarg in self.units and
                    self.units[kwarg] != self._ref_units[kwarg]):
                # special unit defined
                # convert to reference unit for calculations
                kwargs[kwarg] = cfunits.Units.conform(
                    kwargs[kwarg], self.units[kwarg], self._ref_units[kwarg])
        # also store the quantities
        self.vars = kwargs
github atmos-python / atmos / atmos / solve.py View on Github external
unit_str = kwargs[kwarg]
                remove_kwargs.append(kwarg)
                if not isinstance(unit_str, string_types):
                    raise TypeError('units must be strings')
                self.units[var] = cfunits.Units(unit_str)
        for kwarg in remove_kwargs:
            kwargs.pop(kwarg)
        # make sure the remaining variables are quantities
        self._ensure_quantities(*kwargs.keys())
        # convert quantities to reference units
        for kwarg in kwargs:
            if (kwarg in self.units and
                    self.units[kwarg] != self._ref_units[kwarg]):
                # special unit defined
                # convert to reference unit for calculations
                kwargs[kwarg] = cfunits.Units.conform(
                    kwargs[kwarg], self.units[kwarg], self._ref_units[kwarg])
        # also store the quantities
        self.vars = kwargs
github atmos-python / atmos / atmos / solve.py View on Github external
else:  # no solution caching for this class
            funcs, func_args, extra_values = \
                _get_shortest_solution(args, tuple(self.vars.keys()), (),
                                       self.methods)
        # Above method completed successfully if no ValueError has been raised
        # Calculate each quantity we need to calculate in order
        for i, func in enumerate(funcs):
            # Compute this quantity
            value = func(*[self.vars[varname] for varname in func_args[i]])
            # Add it to our dictionary of quantities for successive functions
            self.vars[extra_values[i]] = value
        return_list = []
        for arg in args:
            # do corrections for non-standard units
            if arg in self.units and self.units[arg] != self._ref_units[arg]:
                self.vars[arg] = cfunits.Units.conform(
                    self.vars[arg], self._ref_units[arg], self.units[arg])
            return_list.append(self.vars[arg])
        if self._debug:
            # We should return a list of funcs as the last item returned
            if len(return_list) == 1:
                return _check_scalar(return_list[0]), funcs
            else:
                return ([_check_scalar(val) for val in return_list] +
                        [funcs, ])
        else:
            # no function debugging, just return the quantities
            if len(args) == 1:
                return _check_scalar(return_list[0])
            else:
                return [_check_scalar(val) for val in return_list]
github NCPP / ocgis / src / ocgis / util / logging_ocgis.py View on Github external
def get_versions():
    try:
        import cfunits
    except ImportError:
        v_cfunits = None
    else:
        v_cfunits = cfunits.__version__
    try:
        import cf_units
    except ImportError:
        v_cf_units = None
    else:
        v_cf_units = cf_units.__version__
    try:
        from ocgis.regrid.base import ESMF
    except ImportError:
        v_esmf = None
    else:
        v_esmf = ESMF.__release__
    try:
        import icclim
    except ImportError:
        v_icclim = None

cfunits

A python interface to UNIDATA's UDUNITS-2 package with CF extensions

MIT
Latest version published 8 months ago

Package Health Score

52 / 100
Full package analysis

Similar packages