mcpField
P
pint-units

pint-units

github.com/soljourner開発9543 回インストール51 週間前に更新
リポジトリ

pint-units について

pint-unitsは、物理量を扱うPython Pintを紹介するスキルです。単位変換、次元の整合性確認、単位付き計算を取り上げます。

主な機能

  1. 01互換性のある単位の自動変換
  2. 02次元の整合性チェック
  3. 03単位付き算術演算
  4. 04NumPy配列との連携
  5. 05カスタム単位の定義
  6. 06温度とオフセット単位の処理

活用シーン

  1. 01工学計算で圧力や流量の単位を変換
  2. 02速度や力の式の次元を確認
  3. 03NumPy配列で単位付き計算

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/soljourner/claude-engineering-skills --skill pint-units

インストール後、Claude Code で/pint-unitsを入力して読み込まれたか確認します。

同梱ファイルexamples.py

詳細

Pint 単位スキル

概要

Pint は、単位付きの物理量を扱うための Python パッケージです。次の機能を備えています。

  • 単位の自動変換
  • 次元解析と整合性チェック
  • 単位を考慮した算術演算
  • NumPy 配列との統合
  • カスタム単位定義のサポート
  • 温度変換(オフセット単位を含む)
  • 科学表記と書式設定

Pint は単位変換の誤りをなくし、工学計算における次元の整合性を確保するため、物理量を扱うあらゆる技術業務に不可欠です。

インストール

pip install pint

NumPy および Pandas との統合には、次を使用します。

pip install pint[numpy]

基本的な使い方

物理量の作成

Pint の物理量は、数値(大きさ)と単位で構成されます。

from pint import UnitRegistry

# Create unit registry (do this once per module)
ureg = UnitRegistry()

# Define quantities with units
distance = 100 * ureg.meter
time = 5 * ureg.second
pressure = 50 * ureg.psi

# Alternative syntax using string parsing
flow_rate = ureg('250 gallons/minute')
temperature = ureg('75 degF')
viscosity = ureg('1.5 centipoise')

# Access magnitude and units
print(f"Distance magnitude: {distance.magnitude}")  # 100
print(f"Distance units: {distance.units}")  # meter
単位変換

互換性のある単位間で自動的に変換します。

# Length conversions
distance = 100 * ureg.meter
print(distance.to('feet'))  # 328.084 foot
print(distance.to('kilometer'))  # 0.1 kilometer

# Pressure conversions
pressure = 100 * ureg.psi
print(pressure.to('bar'))  # 6.895 bar
print(pressure.to('pascal'))  # 689475.7 pascal

# Flow rate conversions
flow = 500 * ureg.gallons / ureg.minute
print(flow.to('liter/second'))  # 31.546 liter/second
print(flow.to('m**3/hour'))  # 113.562 meter**3/hour

# Temperature conversions (handles offset units)
temp = 75 * ureg.degF
print(temp.to('degC'))  # 23.889 degree_Celsius
print(temp.to('kelvin'))  # 297.039 kelvin

次元解析

Pint は、計算における次元の整合性を確保します。

# Velocity = Distance / Time
distance = 100 * ureg.meter
time = 5 * ureg.second
velocity = distance / time
print(velocity)  # 20.0 meter/second

# Force = Mass × Acceleration
mass = 10 * ureg.kg
acceleration = 9.81 * ureg.meter / ureg.second**2
force = mass * acceleration
print(force)  # 98.1 kilogram·meter/second²
print(force.to('newton'))  # 98.1 newton

# Dimensional consistency check
try:
    invalid = (100 * ureg.meter) + (50 * ureg.second)  # ❌ ERROR
except Exception as e:
    print(f"Error: Cannot add length and time")

# Correct operation
total_distance = (100 * ureg.meter) + (50 * ureg.feet)  # ✓ OK
print(total_distance)  # 115.24 meter

単位を考慮した計算

流体流量の計算
# Calculate volumetric flow rate from velocity and area
velocity = 3.5 * ureg.meter / ureg.second
diameter = 150 * ureg.millimeter
area = 3.14159 * (diameter/2)**2

flow_rate = velocity * area
print(flow_rate.to('liter/second'))  # 61.86 liter/second
print(flow_rate.to('gpm'))  # 1638.1 gallon/minute

# Reynolds number calculation
density = 998 * ureg.kg / ureg.meter**3
viscosity = 1.0 * ureg.centipoise  # Common unit in industry
Re = (density * velocity * diameter) / viscosity
print(Re.to_base_units())  # Dimensionless: 523170.0
ポンプ動力の計算
# Hydraulic power: P = ρ × g × Q × H
flow_rate = 100 * ureg.meter**3 / ureg.hour
head = 50 * ureg.meter
density = 1000 * ureg.kg / ureg.meter**3
gravity = 9.81 * ureg.meter / ureg.second**2

hydraulic_power = density * gravity * flow_rate * head
print(hydraulic_power.to('kilowatt'))  # 13.625 kilowatt
print(hydraulic_power.to('horsepower'))  # 18.27 horsepower

# With pump efficiency
efficiency = 0.75 * ureg.dimensionless
shaft_power = hydraulic_power / efficiency
print(shaft_power.to('kilowatt'))  # 18.17 kilowatt
圧力損失の計算
# Darcy-Weisbach equation: ΔP = f × (L/D) × (ρV²/2)
friction_factor = 0.018 * ureg.dimensionless
length = 100 * ureg.meter
diameter = 0.15 * ureg.meter
velocity = 2.5 * ureg.meter / ureg.second
density = 1000 * ureg.kg / ureg.meter**3

pressure_drop = friction_factor * (length/diameter) * (density * velocity**2 / 2)
print(pressure_drop.to('pascal'))  # 37500.0 pascal
print(pressure_drop.to('psi'))  # 5.44 pound_force_per_square_inch
print(pressure_drop.to('bar'))  # 0.375 bar

# Convert to head loss
head_loss = pressure_drop / (density * gravity)
print(head_loss.to('meter'))  # 3.822 meter
print(head_loss.to('feet'))  # 12.54 foot

配列の操作

Pint は、配列演算で NumPy とシームレスに連携します。

import numpy as np
from pint import UnitRegistry

ureg = UnitRegistry()

# Create array with units
flow_rates = np.array([50, 75, 100, 125, 150]) * ureg.gpm
heads = np.array([80, 75, 65, 50, 30]) * ureg.meter

# Array operations preserve units
powers = (flow_rates * heads * ureg.kg/ureg.meter**3 * 9.81*ureg.meter/ureg.second**2)
print(powers.to('kilowatt'))
# [2.48 3.72 4.95 6.19 7.43] kilowatt

# Statistical operations
mean_flow = np.mean(flow_rates)
std_flow = np.std(flow_rates)
print(f"Mean flow: {mean_flow.to('liter/minute'):.1f}")
print(f"Std dev: {std_flow.to('liter/minute'):.1f}")

# Unit-aware interpolation
target_head = 70 * ureg.meter
target_flow = np.interp(target_head.magnitude, heads[::-1].magnitude,
                        flow_rates[::-1].magnitude) * ureg.gpm
print(f"Flow at {target_head}: {target_flow.to('m**3/hour'):.1f}")

カスタム単位の定義

分野固有の単位を定義します。

# Add custom units to registry
ureg.define('barrel_oil = 42 * gallon = bbl')
ureg.define('standard_cubic_foot = foot**3 = scf')
ureg.define('darcy = centipoise * centimeter**2 / (second * atmosphere) = D')

# Use custom units
oil_volume = 1000 * ureg.barrel_oil
print(oil_volume.to('gallon'))  # 42000.0 gallon
print(oil_volume.to('liter'))  # 158987.3 liter

gas_flow = 5000 * ureg.standard_cubic_foot / ureg.day
print(gas_flow.to('m**3/hour'))  # 5.90 meter**3/hour

permeability = 100 * ureg.darcy
print(permeability.to_base_units())  # Base SI units

単位系のコンテキストマネージャー

単位系を簡単に切り替えます。

from pint import UnitRegistry

ureg = UnitRegistry()

length = 100 * ureg.meter
mass = 50 * ureg.kg

# Default SI units
print(f"Length: {length}")  # 100 meter
print(f"Mass: {mass}")  # 50 kilogram

# Use US customary units
with ureg.context('US'):
    print(f"Length: {length.to('feet')}")  # 328.084 foot
    print(f"Mass: {mass.to('pound')}")  # 110.231 pound

# Use imperial units
with ureg.context('imperial'):
    print(f"Length: {length.to('yard')}")  # 109.361 yard

温度変換

絶対温度と相対温度を正しく扱います。

# Absolute temperatures
temp1 = 25 * ureg.degC
temp2 = temp1.to('degF')
print(temp2)  # 77.0 degree_Fahrenheit

temp3 = 300 * ureg.kelvin
print(temp3.to('degC'))  # 26.85 degree_Celsius

# Temperature differences (delta)
temp_rise = ureg.Quantity(20, ureg.delta_degC)
print(temp_rise.to(ureg.delta_degF))  # 36.0 delta_degree_Fahrenheit

# Heat transfer calculation
mass = 10 * ureg.kg
specific_heat = 4.18 * ureg.kJ / (ureg.kg * ureg.kelvin)
temp_change = 50 * ureg.delta_degC

heat = mass * specific_heat * temp_change
print(heat.to('kJ'))  # 2090.0 kilojoule
print(heat.to('BTU'))  # 1981.9 BTU

書式設定と表示

物理量の表示方法を制御します。

pressure = 150000 * ureg.pascal

# Default format
print(pressure)  # 150000 pascal

# Compact notation
print(f"{pressure:~}")  # 150000 Pa

# Specific precision
print(f"{pressure:.2f}")  # 150000.00 pascal

# Scientific notation
print(f"{pressure:~.2e}")  # 1.50e+05 Pa

# Pretty format
print(f"{pressure:~P}")  # 150000 Pa

# Custom format
print(f"{pressure.to('bar'):.3f~P}")  # 1.500 bar

一般的な工学単位の変換

圧力
pressure = 100 * ureg.psi
# Common conversions
print(pressure.to('bar'))  # 6.895 bar
print(pressure.to('kPa'))  # 689.476 kilopascal
print(pressure.to('MPa'))  # 0.689 megapascal
print(pressure.to('atm'))  # 6.805 atmosphere
print(pressure.to('mmHg'))  # 5171.5 millimeter_Hg
print(pressure.to('inch_H2O'))  # 2767.7 inch_H2O
流量
flow = 100 * ureg.gpm  # gallons per minute
# Common conversions
print(flow.to('liter/minute'))  # 378.541 liter/minute
print(flow.to('m**3/hour'))  # 22.712 meter**3/hour
print(flow.to('ft**3/second'))  # 0.223 foot**3/second
print(flow.to('barrel_oil/day'))  # 3428.57 barrel_oil/day (if defined)
粘度
# Dynamic viscosity
mu = 1.0 * ureg.centipoise
print(mu.to('pascal*second'))  # 0.001 pascal·second
print(mu.to('lbf*second/ft**2'))  # 2.089e-05 pound_force·second/foot²

# Kinematic viscosity
nu = 1.0 * ureg.centistokes
print(nu.to('m**2/second'))  # 1e-06 meter²/second
print(nu.to('ft**2/second'))  # 1.076e-05 foot²/second
エネルギーと動力
energy = 100 * ureg.kWh
print(energy.to('MJ'))  # 360.0 megajoule
print(energy.to('BTU'))  # 341214.2 BTU
print(energy.to('therm'))  # 3.412 therm

power = 50 * ureg.horsepower
print(power.to('kilowatt'))  # 37.285 kilowatt
print(power.to('BTU/hour'))  # 127259.0 BTU/hour
質量流量
mass_flow = 1000 * ureg.kg / ureg.hour
print(mass_flow.to('lb/minute'))  # 36.74 pound/minute
print(mass_flow.to('ton/day'))  # 0.024 metric_ton/day
print(mass_flow.to('g/second'))  # 277.78 gram/second

ベストプラクティス

  1. UnitRegistry は一度だけ作成する:関数内ではなく、モジュールレベルで ureg = UnitRegistry() を定義します
  2. 保存には基本単位を使う:データベースには、一貫した基本単位(SI)で値を保存します
  3. 入力単位を検証する:入力された物理量が想定される次元を持つことを必ず確認します
  4. 無次元量を扱う:単位のない比率には ureg.dimensionless を使用します
  5. 境界で変換する:結果を表示するときにのみ、表示単位に変換します
  6. 互換性を確認する:quantity.check(dimension) を使って次元の整合性を検証します
  7. 明示的に指定する:デフォルトを仮定せず、単位を明示的に定義します
  8. 温度の扱いに注意する:温度差には delta_ 接頭辞を使い、絶対温度と区別します

次元整合性の確認

def calculate_reynolds_number(velocity, diameter, density, viscosity):
    """
    Calculate Reynolds number with automatic dimensional checking.

    Re = ρVD/μ (dimensionless)
    """
    # Pint automatically checks dimensions
    Re = (density * velocity * diameter) / viscosity

    # Verify result is dimensionless
    assert Re.dimensionality == ureg.dimensionless.dimensionality

    # Return magnitude (pure number)
    return Re.to_base_units().magnitude

# Correct usage
rho = 1000 * ureg.kg / ureg.meter**3
V = 2.5 * ureg.meter / ureg.second
D = 0.15 * ureg.meter
mu = 1e-3 * ureg.pascal * ureg.second

Re = calculate_reynolds_number(V, D, rho, mu)
print(f"Reynolds number: {Re:.0f}")  # 375000

# Incorrect usage will raise error
try:
    Re_wrong = calculate_reynolds_number(V, D, rho, rho)  # Wrong dimension
except Exception as e:
    print("Error: Dimensional inconsistency detected")

工学ワークフローとの統合

例:ポンプ性能曲線
import numpy as np
from pint import UnitRegistry

ureg = UnitRegistry()

def pump_curve(flow_rates, coefficients):
    """
    Calculate pump head from flow rate using curve fit.
    H = H0 - A*Q - B*Q²

    Parameters
    ----------
    flow_rates : Quantity array
        Flow rates with units
    coefficients : dict
        'H0', 'A', 'B' with appropriate units

    Returns
    -------
    heads : Quantity array
        Pump heads with units
    """
    H0 = coefficients['H0']
    A = coefficients['A']
    B = coefficients['B']

    heads = H0 - A * flow_rates - B * flow_rates**2
    return heads

# Define pump curve coefficients
coeffs = {
    'H0': 80 * ureg.meter,
    'A': 200 * ureg.meter / (ureg.meter**3/ureg.second),
    'B': 3000 * ureg.meter / (ureg.meter**3/ureg.second)**2
}

# Calculate performance at different flow rates
Q = np.linspace(0, 0.1, 11) * ureg.meter**3 / ureg.second
H = pump_curve(Q, coeffs)

# Display in different units
print("Flow (GPM)  Head (ft)  Head (m)")
print("-" * 40)
for q, h in zip(Q, H):
    print(f"{q.to('gpm'):8.0f~P}  {h.to('feet'):8.1f~P}  {h.to('meter'):7.1f~P}")

トラブルシューティング

問題:DimensionalityError

原因:互換性のない単位を持つ物理量を加算または比較しようとしています 解決策:すべての項が同じ次元を持つことを確認するか、明示的に変換します

問題:UndefinedUnitError

原因:レジストリに定義されていない単位を使用しています 解決策:ureg.define() を使ってカスタム単位を定義するか、スペルを確認します

問題:オフセット単位(温度)に関するエラー

原因:絶対温度と相対温度の単位が混在しています 解決策:温度差には delta_degC を使用し、絶対温度には通常の degC を使用します

問題:計算で単位が失われる

原因:計算の早い段階で .magnitude を使用しています 解決策:最終出力まで物理量を Pint オブジェクトのまま保持します

クイックリファレンスカード

一般的な単位
量単位
長さmeter, foot, inch, mile, kilometer
面積meter2, foot2, acre, hectare
体積liter, gallon, barrel_oil, ft3, m3
質量kilogram, pound, ton, tonne
時間second, minute, hour, day
速度meter/second, ft/second, mph, kph
流量(体積)m3/hour, gpm, liter/minute, ft3/second
流量(質量)kg/second, lb/minute, ton/hour
圧力pascal, bar, psi, atm, mmHg
力newton, lbf, kgf
電力watt, horsepower, BTU/hour
エネルギーjoule, kWh, BTU, calorie
温度degC, degF, kelvin, rankine
粘度(動粘度)pascal*second, poise, centipoise
粘度(運動粘度)m**2/second, stokes, centistokes
簡単な換算
# Create quantity
Q = 100 * ureg.gpm

# Convert
Q.to('liter/minute')  # To specific unit
Q.to_base_units()     # To SI base units
Q.to_compact()        # To compact SI (kilo, mega, etc)

# Check dimensionality
Q.dimensionality      # [length]³/[time]
Q.check('[volume]/[time]')  # Verify dimension

# Access components
Q.magnitude          # Numeric value
Q.units              # Unit object

参考資料

さらに詳しく

  • NIST Special Publication 811:国際単位系(SI)の使用ガイド
  • ISO 80000:量と単位
  • 石油産業の単位に関するAPI規格
  • 工学計算に関するASME規格

コメント