• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python unit_conversion.convert函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中unit_conversion.convert函数的典型用法代码示例。如果您正苦于以下问题:Python convert函数的具体用法?Python convert怎么用?Python convert使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了convert函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: _init_rate_duration

    def _init_rate_duration(self, avg_frac_oil=1):
        '''
        burn duration based on avg_frac_oil content for LEs marked for burn
        __init__ invokes this to initialize all parameters assuming
        frac_water = 0.0
        '''
        # burn rate constant is defined as a thickness rate in m/sec
        _si_area = uc.convert('Area', self.area_units, 'm^2', self.area)

        # rate if efficiency is 100 %
        self._oilwater_thick_burnrate = self._burn_constant * avg_frac_oil
        self._oil_vol_burnrate = (self._burn_constant *
                                  avg_frac_oil ** 2 *
                                  _si_area)

        # burn duration is known once rate is known
        # reset current thickness to initial thickness whenever model is rerun
        self._oilwater_thickness = uc.convert('Length',
                                              self.thickness_units, 'm',
                                              self.thickness)

        burn_duration = ((self._oilwater_thickness - self._min_thickness) /
                         self._oilwater_thick_burnrate)

        self._active_range = (self.active_range[0],
                              self.active_range[0] +
                              timedelta(seconds=burn_duration))
开发者ID:NOAA-ORR-ERD,项目名称:PyGnome,代码行数:27,代码来源:cleanup.py


示例2: _get_mass

    def _get_mass(self, substance, amount, units):
        '''
        return 'amount' in units of 'kg' for specified substance
        uses the density corresponding with API temperature
        '''
        if units in self.valid_mass_units:
            rm_mass = uc.convert('Mass', units, 'kg', amount)
        else:   # amount must be in volume units
            rm_vol = uc.convert('Volume', units, 'm^3', amount)
            rm_mass = substance.get_density() * rm_vol

        return rm_mass
开发者ID:sandhujasmine,项目名称:PyGnome,代码行数:12,代码来源:cleanup.py


示例3: _convert_units

    def _convert_units(self, data, coord_sys, from_unit, to_unit):
        '''
        method to convert units for the 'value' stored in the
        date/time value pair
        '''
        if from_unit != to_unit:
            data[:, 0] = uc.convert('Velocity', from_unit, to_unit, data[:, 0])

            if coord_sys == coord_systems.uv:
                data[:, 1] = uc.convert('Velocity', from_unit, to_unit,
                                        data[:, 1])

        return data
开发者ID:NOAA-ORR-ERD,项目名称:PyGnome,代码行数:13,代码来源:wind.py


示例4: test_new_api_oneshot

def test_new_api_oneshot():
    """
    just to make sure basic API works!

    and these are a few that have caused problems...
    """

    assert isclose(unit_conversion.convert('meter', 'foot', 1), 3.28083989501)

    assert isclose(unit_conversion.convert('API', 'SG', 10), 1)

    assert isclose(unit_conversion.convert('meter second-1', 'knot', 1),
                   1.94384)

    assert isclose(unit_conversion.convert('m/s', 'knot', 1), 1.94384)
开发者ID:NOAA-ORR-ERD,项目名称:PyNUCOS,代码行数:15,代码来源:test_unit_conversion.py


示例5: _get_mass

    def _get_mass(self, substance, amount, units):
        """
        return 'amount' in units of 'kg' for specified substance
        uses the density corresponding with API temperature
        """
        if units in self.valid_mass_units:
            rm_mass = uc.convert("Mass", units, "kg", amount)
        else:
            # amount must be in volume units
            water_temp = self.water.get("temperature")
            rho = substance.density_at_temp(water_temp)
            rm_vol = uc.convert("Volume", units, "m^3", amount)

            rm_mass = rho * rm_vol

        return rm_mass
开发者ID:NOAA-ORR-ERD,项目名称:PyGnome,代码行数:16,代码来源:cleanup.py


示例6: sample_oil_to_mock_oil

def sample_oil_to_mock_oil(max_cuts=None, **kwargs):
    '''
    make an Oil object from _sample_oils
    Currently, this has only been tested on sample oils, but should be made
    more general. Assume the kwargs are attributes of Oil object

    This adds following attributes:
    'densities' list containing only one density
    'cuts' list containing equal mass in saturates/aromatics for max cuts
    'resins' and 'asphaltene_content' to None
    '''
    if max_cuts is None:
        max_cuts = 5

    oil = Oil(**kwargs)

    # need to add densities list
    oil.densities = [Density(kg_m_3=uc.convert('density', 'api', 'kg/m^3',
                                               oil.api),
                             ref_temp_k=288.15)]

    if 'kvis' in kwargs:
        for k in kwargs['kvis']:
            oil.kvis.append(KVis(**k))

    add_resin_fractions(None, oil)
    add_asphaltene_fractions(None, oil)

    # add cuts - all mass goes into saturates/aromatics for now
    mass_left = 1.0
    mass_left -= sum([f.fraction for f in oil.sara_fractions
                      if f.sara_type in ('Resins', 'Asphaltenes')])

    oil.cuts = []
    prev_mass_frac = 0.0

    summed_boiling_points = []
    for t, f in get_boiling_points_from_api(max_cuts, mass_left, oil.api):
        added_to_sums = False

        for idx, [ut, summed_value] in enumerate(summed_boiling_points):
            if np.isclose(t, ut):
                summed_boiling_points[idx][1] += f
                added_to_sums = True
                break

        if added_to_sums is False:
            summed_boiling_points.append([t, f])

    for t_i, fraction in summed_boiling_points:
        oil.cuts.append(Cut(fraction=prev_mass_frac + fraction,
                            vapor_temp_k=t_i))
        prev_mass_frac += fraction

    add_molecular_weights(None, oil)
    add_saturate_aromatic_fractions(None, oil)
    add_component_densities(None, oil)
    adjust_resin_asphaltene_fractions(None, oil)

    return oil
开发者ID:liuy0813,项目名称:PyGnome,代码行数:60,代码来源:mock_oil.py


示例7: get

    def get(self, attr, unit=None):
        '''
        return value in desired unit. If None, then return the value in SI
        units. The user_unit are given in 'units' attribute and each attribute
        carries the value in as given in these user_units.
        '''
        val = getattr(self, attr)

        if unit is None:
            # Note: salinity only have one units since we don't
            # have any conversions for them in unit_conversion yet - revisit
            # this per requirements
            if (attr not in self._si_units or
                    self._si_units[attr] == self._units[attr]):
                return val
            else:
                unit = self._si_units[attr]

        if unit in self._units_type[attr][1]:
            return uc.convert(self._units_type[attr][0], self.units[attr],
                              unit, val)
        else:
            # log to file if we have logger
            ex = uc.InvalidUnitError((unit, self._units_type[attr][0]))
            self.logger.error(str(ex))
            raise ex
开发者ID:NOAA-ORR-ERD,项目名称:PyGnome,代码行数:26,代码来源:environment.py


示例8: link_refined_fuel_oil_2

def link_refined_fuel_oil_2(session):
    '''
       Category Name:
       - Fuel oil #2/Diesel/Heating Oil
       Sample Oils:
       - Diesel
       - Heating Oil
       - No. 2 Distillate
       Density Criteria:
       - 30 <= API < 39
       Kinematic Viscosity Criteria:
       - 2.5 < v <= 4.0 cSt @ 38 degrees Celcius
    '''
    top, categories = get_categories_by_names(session, 'Refined',
                                              ('Fuel Oil 2',
                                               'Diesel',
                                               'Heating Oil'))

    oils = get_oils_by_api(session, 'Refined',
                           api_min=30.0, api_max=39.0)

    count = 0
    category_temp = 273.15 + 38
    for o in oils:
        o_estim = OilWithEstimation(o)
        viscosity = uc.convert('Kinematic Viscosity', 'm^2/s', 'cSt',
                               o_estim.kvis_at_temp(category_temp))

        if viscosity > 2.5 or viscosity <= 4.0:
            o.categories.extend(categories)
            count += 1

    logger.info('{0} oils added to {1} -> {2}.'
                .format(count, top.name, [n.name for n in categories]))
    transaction.commit()
开发者ID:NOAA-ORR-ERD,项目名称:OilLibrary,代码行数:35,代码来源:init_categories.py


示例9: link_refined_ifo

def link_refined_ifo(session):
    '''
       Category Name:
       - Intermediate Fuel Oil
       Sample Oils:
       - IFO 180
       - Fuel Oil #4
       - Marine Diesel
       Density Criteria:
       - 15 <= API < 30
       Kinematic Viscosity Criteria:
       - 4.0 < v < 200.0 cSt @ 38 degrees Celcius
    '''
    top, categories = get_categories_by_names(session, 'Refined',
                                              ('Intermediate Fuel Oil',))

    oils = get_oils_by_api(session, 'Refined',
                           api_min=15.0, api_max=30.0)

    count = 0
    category_temp = 273.15 + 38
    for o in oils:
        o_estim = OilWithEstimation(o)
        viscosity = uc.convert('Kinematic Viscosity', 'm^2/s', 'cSt',
                               o_estim.kvis_at_temp(category_temp))

        if viscosity > 4.0 or viscosity < 200.0:
            o.categories.extend(categories)
            count += 1

    logger.info('{0} oils added to {1} -> {2}.'
                .format(count, top.name, [n.name for n in categories]))
    transaction.commit()
开发者ID:NOAA-ORR-ERD,项目名称:OilLibrary,代码行数:33,代码来源:init_categories.py


示例10: link_refined_fuel_oil_6

def link_refined_fuel_oil_6(session):
    '''
       Category Name:
       - Fuel Oil #6/Bunker/Heavy Fuel Oil/Group V
       Sample Oils:
       - Bunker C
       - Residual Oil
       Density Criteria:
       - API < 15
       Kinematic Viscosity Criteria:
       - 200.0 <= v cSt @ 50 degrees Celcius
    '''
    top, categories = get_categories_by_names(session, 'Refined',
                                              ('Fuel Oil 6 (HFO)',
                                               'Bunker',
                                               'Heavy Fuel Oil',
                                               'Group V'))

    oils = get_oils_by_api(session, 'Refined',
                           api_min=0.0, api_max=15.0)

    count = 0
    category_temp = 273.15 + 50
    for o in oils:
        o_estim = OilWithEstimation(o)
        viscosity = uc.convert('Kinematic Viscosity', 'm^2/s', 'cSt',
                               o_estim.kvis_at_temp(category_temp))

        if viscosity >= 200.0:
            o.categories.extend(categories)
            count += 1

    logger.info('{0} oils added to {1} -> {2}.'
                .format(count, top.name, [n.name for n in categories]))
    transaction.commit()
开发者ID:NOAA-ORR-ERD,项目名称:OilLibrary,代码行数:35,代码来源:init_categories.py


示例11: show_uncategorized_oils

def show_uncategorized_oils(session):
    oils = (session.query(Oil)
            .filter(Oil.categories == None)
            .all())

    fd = open('temp.txt', 'w')
    fd.write('adios_oil_id\t'
             'product_type\t'
             'api\t'
             'viscosity\t'
             'pour_point\t'
             'name\n')

    logger.info('{0} oils uncategorized.'.format(len(oils)))

    for o in oils:
        o_estim = OilWithEstimation(o)
        if o.api >= 0:
            if o.api < 15:
                category_temp = 273.15 + 50
            else:
                category_temp = 273.15 + 38

            viscosity = uc.convert('Kinematic Viscosity', 'm^2/s', 'cSt',
                                   o_estim.kvis_at_temp(category_temp))
        else:
            viscosity = None

        fd.write('{0.imported.adios_oil_id}\t'
                 '{0.imported.product_type}\t'
                 '{0.api}\t'
                 '{1}\t'
                 '({0.pour_point_min_k}, {0.pour_point_max_k})\t'
                 '{0.name}\n'
                 .format(o, viscosity))
开发者ID:NOAA-ORR-ERD,项目名称:OilLibrary,代码行数:35,代码来源:init_categories.py


示例12: test_prepare_for_model_run

 def test_prepare_for_model_run(self):
     ''' check _oilwater_thickness, _burn_duration is reset'''
     self.burn._oilwater_thickness = 0.002   # reached terminal thickness
     self.burn.prepare_for_model_run(self.sc)
     assert (self.burn._oilwater_thickness ==
             uc.convert('Length', self.burn.thickness_units, 'm',
                        self.burn.thickness))
开发者ID:liuy0813,项目名称:PyGnome,代码行数:7,代码来源:test_cleanup.py


示例13: test_update_active_start

    def test_update_active_start(self):
        '''
        active stop should be updated if we update active start or thickness
        '''
        burn = Burn(self.area,
                    self.thick,
                    active_range=(active_start, InfDateTime('inf')),
                    name='test_burn',
                    on=False)   # this is ignored!

        # use burn constant for test - it isn't stored anywhere
        duration = ((uc.convert('Length', burn.thickness_units, 'm',
                                burn.thickness) -
                     burn._min_thickness) /
                    burn._burn_constant)

        assert (burn.active_range[1] ==
                burn.active_range[0] + timedelta(seconds=duration))

        # after changing active start, active stop should still match the
        # duration.
        burn.active_range = (burn.active_range[0] + timedelta(days=1),
                             burn.active_range[1])
        assert (burn.active_range[1] ==
                burn.active_range[0] + timedelta(seconds=duration))
开发者ID:NOAA-ORR-ERD,项目名称:PyGnome,代码行数:25,代码来源:test_cleanup.py


示例14: Calculate

    def Calculate(self, depth, gas_oil_ratio,
                  oil_jet_velocity=None, oil_jet_density=None,
                  source_pressure=None,
                  output_metric=False):
        if oil_jet_velocity and oil_jet_density:
            # N/m^2  or Pa units (Pascals)
            # equavelent to 950 psi
            source_pressure = (oil_jet_density * (oil_jet_velocity ** 2)) / 2
        elif not source_pressure:
            raise ValueError('need either '
                             'oil_jet_velocity and oil_jet_density, '
                             'or source_pressure')

        if self.metric_inputs:
            depth = convert('Length', 'meter', 'foot', depth)
            gas_oil_ratio = Volume.CubicMeterRatioToScfPerStb(gas_oil_ratio)
            source_pressure = Force.PascalsToPsi(source_pressure)

        # Start-Equation 1.5, page 8
        # Calculating ambient pressure outside leak at depth in psi.
        # We will go off the document, but here are some considerations
        # regarding this calculation:
        # - The ambient atmospheric pressure at sea level is not constant.
        #   It varies with the weather, but averages around 100 kPa
        #   One bar is 100kPa or approximately ambient pressure at sea level
        # - One atmosphere(atm) is also approximately the ambient pressure
        #   at sea level and is equal to 14.7 psi or 1.01325 bar
        # - Ambient water pressure increases linearly with depth.
        #   Roughly, each 10 meters (33 ft) of depth adds another bar
        #   to the ambient pressure.  Assuming the density of sea water
        #   to be 1025 kg/m^3 (in fact it is slightly variable),
        #   pressure increases by 1 atm with each 10 m of depth
        ambient_pressure_at_depth = self.ambient_pressure_at_sea_level + (0.446533 * depth);

        # Start-Equation 1.4, page 8
        # The relative pressure, deltaPrel, difference over the leak point is
        relative_pressure_delta = source_pressure / ambient_pressure_at_depth

        # Start- Table 1.3, page 11
        # Maximum released volume fraction, frel
        max_release_fraction, max_release_occurrence = self.release_fraction_lu[relative_pressure_delta]

        # Start-Section 1.3.5
        #
        # Table 1.4 GOR reduction factors, page 11
        gor_reduction_factor = self.gor_reduction_factor_lu.get_gas_oil_reduction_factor(gas_oil_ratio,
                                                                                         max_release_occurrence)

        if output_metric:
            source_pressure = Force.PsiToPascals(source_pressure)
            ambient_pressure_at_depth = Force.PsiToPascals(ambient_pressure_at_depth)
            max_release_occurrence = Volume.ScfPerStbToCubicMeterRatio(max_release_occurrence)

        return self.gor_results(source_pressure,
                                ambient_pressure_at_depth,
                                relative_pressure_delta,
                                max_release_fraction,
                                max_release_occurrence,
                                gor_reduction_factor)
开发者ID:NOAA-ORR-ERD,项目名称:PyGnome,代码行数:59,代码来源:shallow_depth.py


示例15: test_old_api

def test_old_api(unit_type, unit1, unit2, value, new_value):
    """
    this is a parameterized test
    of all the known values, with the old API
    """
    # now do the test:
    assert isclose(unit_conversion.convert(unit_type, unit1, unit2, value),
                   new_value)
开发者ID:NOAA-ORR-ERD,项目名称:PyNUCOS,代码行数:8,代码来源:test_unit_conversion.py


示例16: test_invalid_unit_convert

def test_invalid_unit_convert():
    with pytest.raises(unit_conversion.InvalidUnitError):
        unit_conversion.convert("length", "flintstones", "meters", 1.0)
    with pytest.raises(unit_conversion.InvalidUnitError):
        unit_conversion.convert("length", "feet", "flintstones", 1.0)

    with pytest.raises(unit_conversion.InvalidUnitError):
        unit_conversion.convert("temperature", "feet", "C", 1.0)
    with pytest.raises(unit_conversion.InvalidUnitError):
        unit_conversion.convert("temperature", "f", "feet", 1.0)
开发者ID:ocefpaf,项目名称:PyNUCOS,代码行数:10,代码来源:test_unit_conversion.py


示例17: plume

def plume(distribution_type='droplet_size',
          distribution='weibull',
          windage_range=(.01, .04),
          windage_persist=900,
          substance_name=None,
          density=None,
          density_units='kg/m^3',
          **kwargs):
    """
    Helper function returns an ElementType object containing 'rise_vel'
    and 'windages'
    initializer with user specified parameters for distribution.

    See below docs for details on the parameters.
    
    NOTE: substance_name or density must be provided 

    :param str distribution_type: default 'droplet_size' available options:

        1. 'droplet_size': Droplet size is samples from the specified
        distribution. Rise velocity is calculated.

        2.'rise_velocity': rise velocity is directly sampled from the specified
        distribution. No droplet size is computed.

    :param distribution='weibull':
    :param windage_range=(.01, .04):
    :param windage_persist=900:
    :param substance_name='oil_conservative':
    :param float density = None:
    :param str density_units='kg/m^3':
    """
    if density is not None:
        # Assume density is at 15 K - convert density to api
        api = uc.convert('density', density_units, 'API', density)
        if substance_name is not None:
            substance = build_oil_props({'name':substance_name, 'api': api}, 2)
        else:
            substance = build_oil_props({'api': api}, 2)
    elif substance_name is not None:
        # model 2 cuts if fake oil
        substance = get_oil_props(substance_name, 2)
    else:
        ex = ValueError()
        ex.message = ("plume substance density and/or name must be provided")
        raise ex
        

    if distribution_type == 'droplet_size':
        return ElementType([InitRiseVelFromDropletSizeFromDist(
                                distribution=distribution, **kwargs),
                            InitWindages(windage_range, windage_persist)],
                           substance)
    elif distribution_type == 'rise_velocity':
        return ElementType([InitRiseVelFromDist(distribution=distribution,
                                                **kwargs),
                            InitWindages(windage_range, windage_persist)],
                           substance)
开发者ID:sandhujasmine,项目名称:PyGnome,代码行数:58,代码来源:element_type.py


示例18: test_OilProps_sample_oil

def test_OilProps_sample_oil(oil, density, units):
    """ compare expected values with values stored in OilProps - make sure
    data entered correctly and unit conversion is correct """

    o = get_oil_props(oil)
    d = uc.convert('density', units, 'kg/m^3', density)

    assert o.name == oil
    assert np.isclose(get_density(o, 273.15 + 15), d)
开发者ID:liuy0813,项目名称:PyGnome,代码行数:9,代码来源:test_oil_props.py


示例19: test_weather_elements

    def test_weather_elements(self, thick, avg_frac_water, units):
        '''
        weather elements and test. frac_water is 0. Test thickness in units
        other than 'm'.

        1) tests the expected burned mass equals 'burned' amount stored in
           mass_balance
        2) also tests the mass_remaining is consistent with what we expect
        3) tests the mass of LEs set for burn equals the mass of oil given
           avg_frac_water and the thickness, and area. Since we cannot have
           a fraction of an LE, the difference should be within the mass of
           one LE.

        Also sets the 'frac_water' to 0.5 for one of the tests just to ensure
        it works.
        '''
        self.spill.set('num_elements', 500)
        thick_si = uc.convert('Length', units, 'm', thick)
        area = (0.5 * self.volume)/thick_si
        burn = Burn(area, thick, active_start, thickness_units=units,
                    efficiency=1.0)

        # return the initial value of burn._oil_thickness - this is starting
        # thickness of the oil
        self._weather_elements_helper(burn, avg_frac_water)

        # following should finally hold true for entire run
        assert np.allclose(amount, self.sc.mass_balance['burned'] +
                           self.sc['mass'].sum(), atol=1e-6)

        # want mass of oil thickness * area gives volume of oil-water so we
        # need to scale this by (1 - avg_frac_water)
        exp_burned = ((thick_si - burn._min_thickness) * (1 - avg_frac_water) *
                      burn.area * self.op.get_density())
        assert np.isclose(self.sc.mass_balance['burned'], exp_burned)

        mask = self.sc['fate_status'] & fate.burn == fate.burn

        # given LEs are discrete elements, we cannot add a fraction of an LE
        mass_per_le = self.sc['init_mass'][mask][0]
        exp_init_oil_mass = (burn.area * thick_si * (1 - avg_frac_water) *
                             self.op.get_density())
        assert (self.sc['init_mass'][mask].sum() - exp_init_oil_mass <
                mass_per_le and
                self.sc['init_mass'][mask].sum() - exp_init_oil_mass >= 0.0)

        exp_mass_remain = (burn._oilwater_thickness * (1 - avg_frac_water) *
                           burn.area * self.op.get_density())
        mass_remain_for_burn_LEs = self.sc['mass'][mask].sum()
        assert np.allclose(exp_mass_remain, mass_remain_for_burn_LEs)

        duration = (burn.active_stop-burn.active_start).total_seconds()/3600
        print ('Current Thickness: {0:.3f}, '
               'Duration (hrs): {1:.3f}').format(burn._oilwater_thickness,
                                                 duration)
开发者ID:liuy0813,项目名称:PyGnome,代码行数:55,代码来源:test_cleanup.py


示例20: test_new_api

def test_new_api(unit_type, unit1, unit2, value, new_value):
    """
    this is a parameterized test
    of all the known values, but with the new API
    """
    # filter out the ones that we know are eliminated
    if unit_conversion.Simplify(unit_type) in ('concentrationinwater',
                                               'oilconcentration'):
        return
    # now do the test:
    assert isclose(unit_conversion.convert(unit1, unit2, value), new_value)
开发者ID:NOAA-ORR-ERD,项目名称:PyNUCOS,代码行数:11,代码来源:test_unit_conversion.py



注:本文中的unit_conversion.convert函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python _testing._Monkey函数代码示例发布时间:2022-05-27
下一篇:
Python unit_base_gen.Base_gen类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap