Coverage for graphica/core/unit_conversion.py: 100.0%
24 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-12 16:38 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-12 16:38 +0000
1"""X 軸の単位の変換(nm / eV / cm^-1 / Hz)。nm 以外は波長に反比例するので、どの組も nm を経由して変換する。"""
2import numpy as np
3from typing import Any
5X_AXIS_UNIT_NONE = 'none'
6X_AXIS_UNIT_NM = 'nm'
7X_AXIS_UNIT_EV = 'eV'
8X_AXIS_UNIT_CM1 = 'cm-1'
9X_AXIS_UNIT_HZ = 'Hz'
11X_AXIS_UNIT_CHOICES = [X_AXIS_UNIT_NONE, X_AXIS_UNIT_NM, X_AXIS_UNIT_EV, X_AXIS_UNIT_CM1, X_AXIS_UNIT_HZ]
13X_AXIS_UNIT_LABELS = {
14 X_AXIS_UNIT_NONE: 'なし',
15 X_AXIS_UNIT_NM: 'nm(波長)',
16 X_AXIS_UNIT_EV: 'eV(エネルギー)',
17 X_AXIS_UNIT_CM1: 'cm⁻¹(波数)',
18 X_AXIS_UNIT_HZ: 'Hz(周波数)',
19}
21# hc [eV·nm]
22_EV_NM_CONSTANT = 1239.8419843320025
23_WAVENUMBER_NM_CONSTANT = 1.0e7
24# 光速 [m/s] × 1e9
25_FREQUENCY_NM_CONSTANT = 2.99792458e17
27_UNIT_TO_NM_CONSTANT = {
28 X_AXIS_UNIT_EV: _EV_NM_CONSTANT,
29 X_AXIS_UNIT_CM1: _WAVENUMBER_NM_CONSTANT,
30 X_AXIS_UNIT_HZ: _FREQUENCY_NM_CONSTANT,
31}
34def convert_x_axis_unit(value: Any, from_unit: str, to_unit: str) -> Any:
35 """from_unit から to_unit へ変換する。
37 波長 0 は例外にせず inf / nan にする(secondary_xaxis の関数に使うので、ゼロ除算の警告も抑える)。
38 """
39 value = np.asarray(value, dtype=float)
40 if from_unit == to_unit:
41 return value
43 with np.errstate(divide='ignore', invalid='ignore'):
44 if from_unit == X_AXIS_UNIT_NM:
45 wavelength_nm = value
46 else:
47 wavelength_nm = _UNIT_TO_NM_CONSTANT[from_unit] / value
49 if to_unit == X_AXIS_UNIT_NM:
50 return wavelength_nm
51 return _UNIT_TO_NM_CONSTANT[to_unit] / wavelength_nm