単位の文字列表現法

単位を文字列表現に変換する

この方法をコントロールすることができます Quantity そして UnitBase 属性はオブジェクトを文字列として表現する. Python Format String Syntax (以下に使用する f-strings )。

数量については、フォーマット説明子、例えば 0.003f 応用されることになります Quantity 値は単位に影響を与えない.説明符,如如 20s 文字列にのみ適用されます Quantity それがそうです。

実例.

レンダリングするには、以下の操作を実行してください Quantity あるいは…。 UnitBase 文字列形式のオブジェクト::

>>> from astropy import units as u
>>> import numpy as np
>>> q = 10.5 * u.km
>>> q
<Quantity  10.5 km>
>>> f"{q}"
'10.5 km'
>>> f"{q:+0.03f}"
'+10.500 km'
>>> f"{q:20s}"
'10.5 km             '

フォーマット値と単位を区別するには、アクセスすることができます Quantity フォーマット文字列のクラス属性::

>>> q = 10.5 * u.km
>>> q
<Quantity  10.5 km>
>>> f"{q.value:0.003f} in {q.unit:s}"
'10.500 in km'

なぜなら numpy 配列は多くのフォーマット説明子を受け入れず,次のような説明子を用いる. 0.003f 応用されています numpy 配列または非スカラー Quantity それがそうです。使用 numpy.array_str() 代わりに。例えば:

>>> q = np.linspace(0,1,10) * u.m
>>> f"{np.array_str(q.value, precision=1)} {q.unit}"  
'[0.  0.1 0.2 0.3 0.4 0.6 0.7 0.8 0.9 1. ] m'

NumPyドキュメントを表示し、より多くの例を理解する numpy.array_str() それがそうです。

Units, or the unit part of a quantity, can also be formatted in a number of different styles. By default, the string format used is referred to as the "generic" format, which is based on syntax of the FITS standard format for representing units, but supports all of the units defined within the astropy.units framework, including user-defined units. The format specifier (and to_string) functions also take an optional parameter to select a different format, including "latex", "unicode", "cds", and others, defined below.

>>> f"{q.value:0.003f} in {q.unit:latex}"  
'10.000 in $\\mathrm{km}$'
>>> fluxunit = u.erg / (u.cm ** 2 * u.s)
>>> f"{fluxunit}"
u'erg / (cm2 s)'
>>> print(f"{fluxunit:console}")
 erg
------
s cm^2
>>> f"{fluxunit:latex}"
u'$\\mathrm{\\frac{erg}{s\\,cm^{2}}}$'
>>> f"{fluxunit:>20s}"
u'       erg / (cm2 s)'

♪the to_string 方法は、単位を文字列にフォーマットする別の方法であり、 format -スタイル使い方::

>>> fluxunit = u.erg / (u.cm ** 2 * u.s)
>>> fluxunit.to_string('latex')
u'$\\mathrm{\\frac{erg}{s\\,cm^{2}}}$'

文字列から単位を作成する

属性は、複数の異なるフォーマットの文字列作成部から生成される。 Unit クラス::

>>> from astropy import units as u
>>> u.Unit("m")
Unit("m")
>>> u.Unit("erg / (s cm2)")
Unit("erg / (cm2 s)")
>>> u.Unit("erg.s-1.cm-2", format="cds")
Unit("erg / (cm2 s)")

注釈

文字列作成ユニットから単位言語に対する専用の解析器を使用する必要があり,文字列作成ユニットを用いると性能が低下する.したがって、ユニットオブジェクトを直接使用する方がはるかに速い(例えば、 unit = u.degree / u.minute )を文字列解析ではなく (unit = u.Unit('deg/min') )である。しかし、あなたのユニットがFITSやVOTABLEなどからのファイルフォーマットを定義する場合、この解析器は非常に有用です。

内蔵形式.

astropy.units 以下のフォーマットの解析および作成のサポートを含む:

astropy.units 書き込みも可能ですが、以下のフォーマットのユニットを読み取ることはできません。

  • "latex" :LaTeX数学文法を用いて単位を書く IAU Style Manual ユニットプレゼンテーションについてのアドバイス。IPythonノートのデバイスを印刷すると、このフォーマットが自動的に使用されます。

    >>> fluxunit  
    
    \[\mathm{\frac{erg}{s\,cm^{2}\]
  • "latex_inline" :LaTeX数学文法を用いて単位を書く IAU Style Manual いくつかの定期刊行物によって要求されるように、ユニット陳述は、スコアではなく負の累乗を使用して推薦される(例えば、 Apj and AJ )である。テキストとの連結に最適な単位表現法:

    >>> fluxunit.to_string('latex_inline')  
    
    \[\mathm{erg\,s^{−1}\,cm^{−2}}\]
  • "console" :テキストコンソールに表示するための単位を書き込む複数行表示:

    >>> print(fluxunit.to_string('console'))
     erg
    ------
    s cm^2
    
  • "unicode" :同じように "console" ただし、Unicodeを使用する文字を除く:

    >>> print(u.Ry.decompose().to_string('unicode'))  
                    m² kg
    2.1798721×10-¹⁸ ─────
    
    

識別できない単位

野外で発見された多くの文書は、任意の所与の基準に対応しない単位文字列を持つため、 astropy.units 未解析のセル文字列を格納して渡す一致方式もある.

通常、認識できない単位文字列を伝達することは異常を引き起こす:

>>> # The FITS standard uses 'angstrom', not 'Angstroem'
>>> u.Unit("Angstroem", format="fits")
Traceback (most recent call last):
  ...
ValueError: 'Angstroem' did not parse as fits unit: At col 0, Unit
'Angstroem' not supported by the FITS standard. Did you mean Angstrom
or angstrom? If this is meant to be a custom unit, define it with
'u.def_unit'. To have it recognized inside a file reader or other
code, enable it with 'u.add_enabled_units'. For details, see
https://docs.astropy.org/en/latest/units/combining_and_defining.html

しかし、 Unit 構造関数はキーワードパラメータを持つ parse_strict これは、以下の3つの値のうちの1つを使用して制御することができる。

  • 'raise' :(デフォルト値)ValueError例外を誘発します。

  • 'warn' :警告を発して戻る UnrecognizedUnit 例を挙げましょう

  • 'silent' :1つ戻る UnrecognizedUnit 例を挙げましょう

実例.

認識できない単位文字列を渡すには、以下の操作を実行してください。

>>> x = u.Unit("Angstroem", format="fits", parse_strict="warn")  
WARNING: UnitsWarning: 'Angstroem' did not parse as unit format
'fits': At col 0, 'Angstroem' is not a valid unit in string
'Angstroem' [astropy.units.core]

これが…。 UnrecognizedUnit オブジェクトは,それを作成する際に使用する元の文字列を記憶するため,それを書き戻すことができるが,それに対して実行される任意の意味のある操作(別の単位に変換したり,他の単位を用いて合成したりする)は失敗する.

>>> x.to_string()  
'Angstroem'
>>> x.to(u.km)  
Traceback (most recent call last):
  ...
ValueError: The unit 'Angstroem' is unrecognized.  It can not be
converted to other units.
>>> x / u.m  
Traceback (most recent call last):
  ...
ValueError: The unit 'Angstroem' is unrecognized, so all arithmetic
operations with it are invalid.