Communitygithub.com

不確かさと単位

物理単位の追跡と測定不確かさの伝播を、pintとuncertaintiesライブラリを使って行うスキルです。単位変換、次元チェック、GUM不確かさバジェット、モンテカルロ伝播、有効数字表現など、科学的計算における単位と不確かさの管理を包括的にサポートします。

不確かさと単位 とは?

このスキルは、物理単位を伴う計算や不確かさを報告する必要がある数値計算において、単位変換、不確かさの伝播、GUM不確かさバジェットの構築、カバレッジ係数の決定、結果の丸めと報告、カーブフィットからのパラメータ不確かさの抽出、コード監査、無次元数による次数チェックなどを実施します。pint 0.25.3、uncertainties 3.2.3、NumPy 2.5.1、SciPy 1.18.0(CODATA 2022対応)をサポートし、Python 3.13環境での動作を推奨しています。スキルには6つのローカルCLIツール(propagate_uncertainty.py, uncertainty_budget.py, format_result.py, convert_units.py, audit_units.py, check_plausibility.py)がバンドルされており、オフラインで動作し、コードを実行せずに静的解析や計算を行います。特に、線形近似の妥当性をモンテカルロ法とGUMフレームワークの比較で検証するJCGM 101節8テスト、単位剥ぎ取りや相関破壊などの典型的な失敗パターンを検出するコード監査、無次元数と特性スケールによる物理的妥当性チェックが特徴です。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/uncertainty-and-units

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

不確かさと単位 は何をしますか?

範囲

計算に物理単位が含まれる場合、または報告する数値に不確かさが必要な場合に、このスキルを使用してください。具体的には:

  • 単位間の変換(波長から光子エネルギー、質量から物質量、エネルギーから温度など、物理的な文脈が必要な変換を含む)
  • 測定モデルを通じての不確かさの伝播(入力の相関の有無を問わない)
  • 校正証明書、仕様書、再現性データからのGUM不確かさバジェットの構築
  • カバレッジ係数の選択とk = 2が妥当かどうかの判断
  • 読者が±の意味を理解できるように結果の丸めと記述
  • カーブフィットからパラメータの不確かさを抽出(相関を破棄せずに)
  • 既存の解析コードの監査(暗黙的な単位除去や不確かさ伝播の欠陥の発見)
  • 次元的に一貫した答えが物理的に可能かどうかの確認(オーダー、無次元数、およびそれが示すレジーム)

このスキルは計測学とそれを実装する2つのライブラリをカバーします。統計的推論、モデル選択、研究デザインはカバーしません。これらについてはstatistical-analysis、statistical-power、experimental-designを参照してください。

現在のリリースとインストール

2026-07-26検証済み:

  • pint 0.25.3(2026-03-19リリース)、Python 3.11+が必要
  • uncertainties 3.2.3(2025-04-21リリース)、Python 3.8+が必要
  • NumPy 2.5.1 と SciPy 1.18.0、両方ともPython 3.12+が必要
  • SciPy 1.18.0のscipy.constantsはCODATA 2022を提供。SciPy 1.11以前はCODATA 2018を提供しており、推奨値の一部が異なります。
uv venv --python 3.13
source .venv/bin/activate
uv pip install "pint==0.25.3" "uncertainties==3.2.3" "numpy==2.5.1" "scipy==1.18.0"

pint-pandasとpint-xarrayは単位対応の列と配列を追加し、別途インストールが必要です。

譲れないワークフロー

  1. 入力時に単位を付与し、出力時のみ剥がす。 関数境界ではureg.wrapsまたはm_as("unit")で変換し、計算途中で行わないこと。
  2. 計算前に測定モデルを明示的に記述する。 推定値がゼロの補正も含めること。モデルから補正を除外すると、その不確かさがバジェットから漏れます。
  3. すべての入力に4つの情報を与える: 推定値、標準不確かさ、不確かさの分布、自由度。
  4. タイプB評価を正しい除数で変換する。 証明書の拡張不確かさは記載されたkで除算。矩形分布の極限はsqrt(3)で除算。
  5. 組み合わせる前に相関を特定する。 同じ標準器で校正された入力、同じ計器で測定された入力、同じフィットから得られた入力は相関しています。
  6. 感度係数を計算し、生の不確かさではなくc_i * u(x_i)からバジェットを読み取る。
  7. 線形化を確認する。 GUMフレームワークと並行してモンテカルロ法を実行し、JCGM 101節8の比較を適用する。失敗した場合はモンテカルロ結果を報告する。
  8. kを有効自由度から選択する。 習慣ではなく。
  9. まず不確かさを丸め、次に値を同じ小数点桁に丸める。
  10. ±が何であるかを明記する。 標準か拡張か、k、カバレッジ確率、方法を記載する。
  11. 報告前に大きさを常識的にチェックする。 次元的に一貫した結果でも、物理的に不可能な場合がある。既知のスケールや無次元数と比較し、そのレジームで仮定が成り立つことを確認する。

このスキルが防止する失敗例

以下の各コードはエラーなく実行され、もっともらしい数値を生成します。

不明なスケールでの単位剥ぎ取り

length = (12.7 * ureg.mm).magnitude          # 12.7 -- 何の?
length = (12.7 * ureg.mm).m_as("m")          # 0.0127 メートル、と明示

.magnitudeは数量がたまたま保持していたものを返します。抽出時に毎回単位を指定してください。

オフセット温度の算術

Q(20, "degC") + Q(5, "degC")     # OffsetUnitCalculusError -- 正しく拒否
Q(20, "degC") + Q(5, "delta_degC")   # 25 degree_Celsius
Q(25, "degC") - Q(20, "degC")        # 5 delta_degree_Celsius

摂氏と華氏は間隔尺度です。温度の不確かさは常に差であり、delta_単位に属します。20 ± 0.5 degCを華氏に変換すると68 degF ± 0.9 delta_degFとなり、1行で2つの異なる変換になります。

乗算で加算する対数単位

Q(10, "dBm") + Q(10, "dBm")   # 0.0001 kilogram**2 * meter**4 / second**6

これは10 mW × 10 mWであり、20 mWでも13 dBmでもありません。何もエラーは発生しません。算術演算の前に線形単位に変換してください。

ラウンドトリップによる相関の破壊

x = ufloat(1.0, 0.1)
x - x                                     # 0.0+/-0
x - ufloat(x.nominal_value, x.std_dev)    # 0.00+/-0.14

公称値と標準偏差から変数を再構築すると、独立した変数が作成されます。浮動小数点数のペアを介するシリアル化も同様です。相関セットを再構築するにはcorrelated_values(values, covariance_matrix)を使用してください。

共分散行列の暗黙的な再スケーリング

popt, pcov = curve_fit(f, x, y, sigma=sigma)                        # デフォルト
popt, pcov = curve_fit(f, x, y, sigma=sigma, absolute_sigma=True)

デフォルトではpcovが縮小カイ二乗で再スケーリングされるため、パラメータの不確かさに適合の良さが吸収され、sigmaを渡さなかった場合と一致します。ある合成直線フィットでは、2つの方法で[0.0364, 0.2154]と[0.0477, 0.2820]という31%の差が生じます。sigmaが実際の標準不確かさを保持している場合は、常にabsolute_sigma=Trueを渡してください。

確認されなかった線形化

y = x² で x = 1.0 ± 0.5 の場合、GUMフレームワークは y = 1.0、u_c = 1.0、95%区間[-0.96, 2.96]を与えます。これは二乗量に対してほとんどが負の値です。モンテカルロ法は平均1.25、u_c = 1.06、最短95%区間[0, 3.32]を与えます。線形伝播ライブラリではこのようなことは教えてくれません。

バンドルされたローカルCLI

すべてのヘルパーはオフラインで動作し、URLやシンボリックリンクを拒否し、入力を制限し、出力をアトミックにプライベート権限で書き込み、--forceなしでは上書きを拒否します。

python skills/uncertainty-and-units/scripts/propagate_uncertainty.py --help
python skills/uncertainty-and-units/scripts/uncertainty_budget.py --help
python skills/uncertainty-and-units/scripts/format_result.py --help
python skills/uncertainty-and-units/scripts/convert_units.py --help
python skills/uncertainty-and-units/scripts/audit_units.py --help
python skills/uncertainty-and-units/scripts/check_plausibility.py --help

propagate_uncertainty.py

同じモデルで両方の伝播方法を実行し、JCGM 101節8の検証テストを適用します。

python skills/uncertainty-and-units/scripts/propagate_uncertainty.py \
  --expression "m / (pi * (d / 2) ** 2 * h)" \
  --variable "m=250.0,0.05" \
  --variable "d=20.0,0.02,rectangular" \
  --variable "h=40.0,0.05,rectangular" \
  --measurand density --unit "g/cm3" --format markdown

各--variableは名前=値,標準不確かさ[,分布[,自由度]]の形式です。分布はnormal、rectangular、triangular、arcsine、exactのいずれかで、モンテカルロサンプリングのみを制御します。相関は--correlation "a,b=0.9"として渡します。長期使用するモデルはJSONの--specファイルで保持します。

式は抽象構文木にパースされ、+ - * / **と固定の関数リストの明示的なウォークによって簡約されます。コンパイルや実行は行われません。

レポートは推定値、u_c、感度係数、パーセントでのバジェット、有効自由度、k、U、両方のモンテカルロカバレッジ区間、および線形化結果を報告してもよいかどうかの判定を提供します。

uncertainty_budget.py

証明書やデータシートに記載されている方法で成分を組み合わせます。

python skills/uncertainty-and-units/scripts/uncertainty_budget.py --template > budget.json
python skills/uncertainty-and-units/scripts/uncertainty_budget.py --spec budget.json --format markdown

各成分は、その除数を決定するdistributionを指定します。expandedはそのcoverage_factorで除算、rectangularはsqrt(3)、triangularはsqrt(6)、arcsineはsqrt(2)、normalは1で除算します。オプションでsensitivity、dof、relative: trueを指定できます。ツールはu_c、Welch-Satterthwaiteの有効自由度、t分布からのk、およびUを計算し、タイプA成分に自由度がない場合、nu_effが小さくてk = 2が誤っている場合、1つの成分が支配的である場合、タイプB成分がnormalと宣言されているが実際には未分割の拡張不確かさである可能性がある場合に警告します。

format_result.py

python skills/uncertainty-and-units/scripts/format_result.py \
  --value 12.34567 --uncertainty 0.02345 --unit mm \
  --coverage-factor 2.26 --coverage-probability 0.95

12.346 ± 0.023 mm、12.346(23) mm、科学的表記とLaTeX形式、および数値に付随する説明文を返します。不確かさが1または2で始まる場合に有効数字1桁が要求された場合、および不確かさが推定値を超える場合に警告します。

convert_units.py

python skills/uncertainty-and-units/scripts/convert_units.py \
  --value 532 --unit nm --to eV --context spectroscopy --uncertainty 0.5

python skills/uncertainty-and-units/scripts/convert_units.py \
  --value 1.0 --unit g --to mol --context chemistry --context-parameter "mw=180.156 g/mol"

不確かさを変換の局所微分を通して伝播します。これは、コンテキスト変換が比例ではなく逆数であるため重要です。変換にコンテキストが必要な場合はエラーメッセージにコンテキスト名を表示し、オフセット単位と対数単位をフラグします。--list-contextsはレジストリが定義するものを表示します。

audit_units.py

既存の解析コードの静的レビュー。パースはしますが、インポートや実行はしません。

python skills/uncertainty-and-units/scripts/audit_units.py \
  --input analysis.py --format markdown --fail-on medium
ルール重大度検出内容
UNIT001medium1つのモジュール内の2番目のUnitRegistry — レジストリ間のValueError
UNIT002mediumどこにもdelta_単位がないオフセット温度単位
UNIT003high先行する.to(...)や.m_as(...)なしの.magnitude
UNIT004medium対数単位(+が乗算になる)
UNC001highabsolute_sigmaなしのcurve_fit
UNC002mediumddofなしのnp.std / np.var
UNC003mediumuncertaintiesを使用するモジュールでのmathまたはnumpy関数
UNC004high.nominal_valueと.std_devから再構築されたufloat
CONST001lowCODATA定数の0.1%以内のリテラル

終了ステータスは、--fail-on(デフォルトhigh)に一致する発見があった場合に1になります。これにより、pre-commitやCIチェックとして使用可能になります。

ルールはヒューリスティックであるため、偽陽性はディレクティブコメントで抑制します。行末に付けてその行をカバーするか、単独行で次の行をカバーします:

value = quantity.magnitude  # audit-units: ignore UNIT003 -- 上流で既に変換済み

# audit-units: ignore UNC003 -- ここでの引数はプレーンなfloat配列
scaled = np.log10(counts)

# audit-units: ignore-file CONST001はモジュール全体をカバーし、ルールを指定しないとすべてを抑制します。抑制は報告書にカウントされて表示されるため、すべてを沈黙させるファイルでもその旨が明記されます。

check_plausibility.py

次元の一貫性は物理的可能性を保証しません。2mの細胞やキャピラリー内のレイノルズ数4e7は、すべての単位チェックを通過します。このツールは、一連の数量を無次元数、特性スケール、厳選された大きさの帯域に対してテストし、数値を報告する前に各式の次元性を検証します。

python skills/uncertainty-and-units/scripts/check_plausibility.py \
  --quantity "density=1060 kg/m**3" --quantity "velocity=0.5 mm/s" \
  --quantity "length=8 um" --quantity "viscosity=3.5 mPa*s" \
  --group reynolds --format markdown
# Re = 0.001211 -- 層流(円管、長さ = 直径)

python skills/uncertainty-and-units/scripts/check_plausibility.py \
  --quantity "diameter=2 m" --band "eukaryotic_cell_diameter=diameter"
# implausible: 5-100 umの範囲から4.3桁外れ

--groupは14の無次元数の1つを評価し、システムが置かれるレジームを命名します。--scaleは拡散時間、デバイ長、ストークス沈降速度などの特性スケールを計算します。--bandは提供された数量を観測範囲と比較します。--listは、各式が必要とする入力とともに全カタログを表示します。

物理定数(k_B、N_A、R_gas、g_earthなど)は提供しなくてもすべての式で利用可能であり、リテラルとして記述されるのではなく実行時にscipy.constantsから読み取られるため、SciPyが提供するCODATAリリースを追跡します。

次元性チェックが重要です。式が動粘度を必要としているのに動粘度(両方とも「粘度」と呼ばれ、水について表にまとめられており、ρの係数分だけ異なる)を渡すと、数値が計算される前に拒否されます:

error: viscosity must have dimensionality [mass] / ([length] * [time]),
       but m²/s is [length] ** 2 / [time]

終了ステータスは、判定が--fail-on(デフォルトimplausible。帯域の1桁以内の値はquestionable)に一致した場合に1になります。しきい値はソフトエッジを持つ慣例であり、相関関係が適合された幾何形状を想定しています。各ケースで使用する特性長についてはreferences/plausibility-scales.mdを参照してください。

伝播方法の選択

状況方法
線形またはほぼ線形のモデル、ほぼ正規の入力、大きな自由度GUMフレームワークのみ
入力の±2uにわたる非線形性両方を実行し、節8テストを適用
任意の入力で相対不確かさが約20%以上両方を実行し、節8テストを適用
モデルが不連続または定義域境界を含むモンテカルロ法のみ
非対称な出力分布が予想されるモンテカルロ法のみ
無視できない相関があり、共分散行列が利用可能両方を実行、GUMフレームワークは線形化共分散則を使用

節8テストは、モンテカルロ法の95%信頼区間がGUMフレームワークの区間から両端の有効桁数1桁以内にあることを要求します。このテストに合格した場合、線形化結果を報告できます。合格しない場合は、モンテカルロ区間とその平均を報告します。

参考文献

  • JCGM 100:2008 計測における不確かさの表現のガイド(GUM)
  • JCGM 101:2008 GUM 補遺1:モンテカルロ法による分布の伝播 — 節8の比較手順
  • JCGM 102:2011 GUM 補遺2:多変量測定量のモデル — 相関を伴う拡張
  • NIST TN 1900 不確かさの予算の作成と報告(2016年改訂)
  • BIPM 計量学の国際用語集(VIM、第3版)
  • pint ドキュメンテーション — 単位レジストリ、コンテキスト変換、wrapsデコレータ
  • uncertainties パッケージ ドキュメンテーション — ufloat、umath、correlated_values、covariance_matrix
  • SciPy 定数 — scipy.constants.physical_constantsとCODATA推奨値へのアクセス
  • M. P. Hobson 他「高エネルギー物理学における体系的および統計的不確かさの頻度論的およびベイズ的扱いに関する実用的なガイド」(2010年)、arXiv:1002.2784

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

adaptyv

How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.

aeon

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

alphagenome

Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.

analytical-method-validation

Plan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include

anndata

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

arbor

Autonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g.

arboreto

Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.

astropy

Core Python library for astronomy and astrophysics workflows that need Astropy APIs, including units/quantities, coordinates, FITS I/O, tables, time systems, WCS, and cosmology. Use when implementing or debugging astronomical data analysis code with Astropy.

autoskill

Observe the user

benchling-integration

Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.

bgpt-paper-search

Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.

bids

>

biopython

Comprehensive molecular biology toolkit. Use for sequence manipulation, file parsing (FASTA/GenBank/PDB), phylogenetics, and programmatic NCBI/PubMed access (Bio.Entrez). Best for batch processing, custom bioinformatics pipelines, BLAST automation. For quick lookups use gget; for multi-service integration use bioservices.

bioservices

Unified Python interface to 40+ bioinformatics services. Use when querying multiple databases (UniProt, KEGG, ChEMBL, Reactome) in a single workflow with consistent API. Best for cross-database analysis, ID mapping across services. For quick single-database lookups use gget; for sequence/file manipulation use biopython.

bulk-rnaseq

End-to-end bulk RNA-seq orchestrator — takes raw FASTQ reads through QC and trimming (FastQC, fastp/Trim Galore), alignment and quantification (STAR, Salmon, featureCounts), assembles a gene-level counts matrix, then hands off to differential expression (pydeseq2), pathway/GSEA enrichment (pathway-enrichment), and publication figures (scientific-visualization). Use whenever the user has bulk RNA-seq reads or quant output and wants a complete, reproducible differential-expression workflow — e.g.

cellxgene-census

Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.

cirq

Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.

citation-management

Comprehensive citation management for academic research. Search OpenAlex, PubMed, and Google Scholar for papers, extract accurate metadata, validate citations, and generate properly formatted BibTeX entries. This skill should be used when you need to find papers, verify citation information, convert DOIs to BibTeX, or ensure reference accuracy in scientific writing.

clinical-decision-support

Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.

clinical-reports

Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.

関連スキル