首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >“`pint`”中导出尺寸数量的标准格式

“`pint`”中导出尺寸数量的标准格式
EN

Stack Overflow用户
提问于 2021-11-05 16:20:25
回答 1查看 291关注 0票数 3

TLDR: I希望在一个特定(派生)维度中的pint数量在默认情况下转换为一个预先设置的单元。

详细信息:

我处理5个维度,如下所述。注意,电源价格是派生的维度。

代码语言:javascript
复制
# units.txt

# Base dimensions and their units
hour = [time] = h = hr
megawatthour = [energy] = MWh
euro = [currency] = Eur = €

# Derived dimensions and their units
[power] = [energy] / [time]
megawatt = megawatthour / hour = MW
[price] = [currency] / [energy]
euro_per_MWh = euro / megawatthour  = Eur/MWh

我的问题是:是否可以指定具有尺寸功率的计算量在默认情况下转换为兆瓦?

下面是一个例子:

代码语言:javascript
复制
import pint

ureg = pint.UnitRegistry("units.txt",)
ureg.default_format = ".0f~P"

energy = 100 * ureg.MWh
time = 4 * ureg.h
revenue = 4000 * ureg.euro

price = revenue / energy
power = energy / time

print(energy, time, revenue, price, power) 
# 100 MWh 4 h 4000 Eur 40 Eur/MWh 25 MWh/h

在这里,功率是以MWh/h表示的,因为它的计算方式,我可以通过调用power.to('MW')将其“转换”为MW。是否可以在每次计算此维度中的数量时自动完成此操作?

请注意,对所有数量做一个毯子.to_base_units()会将其恢复到MWh/h。

备注:

  • 我不想把权力作为基本维度。不管怎样,这就把问题推到了价格上。
  • 我知道前缀;我只是把它们放在这里,以使示例尽可能简短。
EN

回答 1

Stack Overflow用户

发布于 2021-11-05 18:32:41

据我所知,Pint目前不支持设置所需的转换首选项。在项目回购和这个问题链接到一系列相关的问题上,有一些关于这个问题的讨论。

您想要的东西可以通过一些自定义代码来实现,但是需要在函数中包装输出。

代码语言:javascript
复制
# units-2.txt

# Base dimensions and their units
hour = [time] = h = hr
megawatt = [power] = MW 
euro = [currency] = Eur = €

# Derived dimensions and their units
[energy] = [power] * [time]
megawatthour = megawatt * hour = MWh
[price] = [currency] / [energy]
euro_per_MWh = euro / megawatthour  = Eur/MWh
代码语言:javascript
复制
import pint

preference = ["Eur/MWh", 'MW']

def beautify(x, preference=preference):
    for preferred_unit in preference:
        try:
            return x.to(preferred_unit)
        except pint.DimensionalityError:
            pass
    # if no preferred unit fits, leave it as it is
    return x

def test_defs(file):
    print(file)
    ureg = pint.UnitRegistry(file,)
    ureg.default_format = ".0f~P"
    energy = 100 * ureg.MWh
    time = 4 * ureg.h
    revenue = 4000 * ureg.euro
    price = revenue / energy
    power = energy / time
    print(time.to_base_units())
    print(f"beautified time: {beautify(time)}")  # Units with no preference remain the same.
    print(power.to_base_units())
    print(f"beautified power: {beautify(power)}")  # Units with preference can be changed.
    print(price.to_base_units())
    print(f"beautified price: {beautify(price)}")  # Units with preference can be changed.

test_defs("units.txt")
test_defs("units-2.txt")

这个会打印出来

代码语言:javascript
复制
units.txt
4 h
beautified time: 4 h
25 MWh/h
beautified power: 25 MW
40 Eur/MWh
beautified price: 40 Eur/MWh
units-2.txt
4 h
beautified time: 4 h
25 MW
beautified power: 25 MW
40 Eur/MW/h
beautified price: 40 Eur/MWh
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69856267

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档