analysis-methods

작성자: nvidia

분석가 에이전트가 pandas, matplotlib, scipy를 사용하여 FHIR 임상 데이터에 대한 정확하고 견고한 Python 분석 코드를 작성하는 방법을 가르칩니다.

npx skills add https://github.com/nvidia/dgx-spark-playbooks --skill analysis-methods

Analysis Code Guidelines

FHIR Helpers Library

Always import the helpers library at the top of every analysis script:

import sys
sys.path.insert(0, '/sandbox/clinical-intelligence/skills/analysis-methods/scripts')
from fhir_helpers import *

Available functions

FunctionUse forHTTP calls
get_patients_with_condition(snomed_code)Find patients with a condition → list of IDs1-2
get_latest_labs_batch(loinc_code, patient_ids)Labs for a cohort → dict: pid → (value, unit, date)1-2
get_all_medications_batch(patient_ids)Meds for a cohort → dict: pid → [med names]1-2
build_cohort_df(patient_ids, loinc, lab_name, drug_check_fn)Full DataFrame with labs + meds2-3
get_latest_lab(patient_id, loinc_code)Lab for ONE patient → (value, unit, date)1
get_medications(patient_id)Meds for ONE patient → [names]1
get_latest_bp(patient_id)BP for ONE patient → (sys, dia, date)1-2
check_drug_class(med_list, drug_names)Check if any med matches drug list → bool0
fhir_get(path, params)Raw FHIR GET → parsed JSON1
get_all_pages(path, params)Paginated FHIR GET → all entries1+
save_chart_to_canvas(fig, filename)Save matplotlib figure to canvas directory0

Performance rules

  • Cohort queries (2+ patients): Use get_latest_labs_batch() and get_all_medications_batch(). These make 1-2 HTTP calls total regardless of patient count.
  • Single patient: Use get_latest_lab(), get_medications(), get_latest_bp().
  • NEVER loop over patients calling get_latest_lab() per patient. Each HTTP call through the sandbox proxy adds 1-3s. For 48 patients = 48 calls = 2+ minutes. The batch function does it in one call.

Execution Rules

  • Run scripts with python (NOT python3)
  • Write a SINGLE Python script for the entire task
  • Write the script to /tmp/<name>.py, then execute it
  • All HTTP inside the sandbox must use subprocess.run(["curl", ...]) — the requests library does NOT work

Mandatory Workflow

STEP 1 - WRITE SCRIPT (import fhir_helpers, write analysis)
STEP 2 - VALIDATE: python /sandbox/clinical-intelligence/scripts/validate_and_run.py --validate-only /tmp/<name>.py
STEP 3 - EXECUTE: python /tmp/<name>.py
STEP 4 - INTERPRET: explain results using clinical-knowledge skill

Code Structure

  1. Imports (always start with fhir_helpers import)
  2. Data collection (use batch functions)
  3. DataFrame construction
  4. Analysis (filters, aggregations)
  5. Visualization -- use save_chart_to_canvas(fig, filename) (NOT plt.savefig)
  6. Summary (print findings)
  7. Disclaimer

Care Gap Analysis Pattern

# Example: diabetes care gap
patients = get_patients_with_condition("44054006")  # SNOMED for diabetes
df = build_cohort_df(patients, "4548-4", "HbA1c",
                     lambda meds: check_drug_class(meds, ["metformin", "insulin", "glipizide"]))

gap = df[(df['HbA1c'] > 9) & (~df['on_target_med'])]
denom = len(df[df['HbA1c'].notna()])
pct = f"{len(gap)/denom*100:.1f}%" if denom > 0 else "N/A (no HbA1c data)"
print(f"Care gap: {len(gap)}/{denom} ({pct})")

Visualization

Always use dark theme. Use save_chart_to_canvas() instead of plt.savefig() directly.

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

plt.style.use('dark_background')
fig, ax = plt.subplots(figsize=(10, 6))
fig.patch.set_facecolor('#1a1a1a')
ax.set_facecolor('#1a1a1a')

# Histogram with NVIDIA green
ax.hist(values, bins=15, color='#76B900', edgecolor='#1a1a1a', alpha=0.85)
ax.axvline(x=threshold, color='#ff4444', linestyle='--', linewidth=2, label=f'Threshold ({threshold})')
ax.set_title("Title", fontsize=14, fontweight='bold', color='white')
ax.legend()
ax.grid(axis='y', alpha=0.2, color='#444444')
ax.text(0.98, 0.95, f"N = {len(values)}", transform=ax.transAxes, fontsize=11, color='#888888', ha='right', va='top')

# MANDATORY: use save_chart_to_canvas (NOT plt.savefig)
save_chart_to_canvas(fig, "chart.png")
plt.close()

Guardrails

  • Never compute statistics on fewer than 5 data points
  • Always report sample size: "45.0% (27 out of 60)"
  • Flag data quality issues if >30% missing
  • Do not fabricate data — report what exists, flag what's missing
  • All charts must include N annotation

Output Format

End every script with:

print(f"\nDisclaimer: This analysis is for research and operational purposes.")
print("Clinical decisions should be made by qualified clinicians.")

nvidia의 다른 스킬

compileiq-debug
nvidia
무언가 잘못되었을 때 사용: Search()가 멈추거나, 모든 평가가 INVALID_SCORE를 반환하거나, 점수가 개선되지 않거나, 모든 설정이 동일한 숫자를 반환하거나, ptxas 오류 등이 발생할 때
create-github-pr
nvidia
gh CLI를 사용하여 GitHub 풀 리퀘스트를 생성합니다. 사용자가 새 PR을 만들거나, 코드 리뷰를 제출하거나, 풀 리퀘스트를 열고자 할 때 사용합니다. 트리거 키워드 -…
nemoclaw-maintainer-cross-issue-sweep
nvidia
다른 열린 이슈들을 스캔하여 주어진 PR이 함께 수정하거나 실수로 망가뜨릴 수 있는 이슈를 찾습니다. 인접 수정 기회와 모순 위험을 file:line…과 함께 출력합니다.
fhir-basics
nvidia
에이전트에게 FHIR R4 API의 작동 방식, 사용 가능한 리소스, 검색 매개변수를 사용한 쿼리 방법, 모든 응답 형식을 올바르게 파싱하는 방법을 가르칩니다…
compileiq-validate-result
nvidia
검색이 완료된 후, 속도 향상을 청구하거나 ACF를 발송하기 전에 사용합니다. dump_results CSV를 로드하고, 상위 K개 후보(단일 목표)를 추출합니다…
changelog-audit
nvidia
릴리스 전에 Warp CHANGELOG.md를 감사합니다: 누락된 항목 복구, 사용자 영향별 정렬, 항목 언어 다듬기, 줄 바꿈, (릴리스 브랜치 모드) 비교 업데이트…
maintain-dynamic-plugins
nvidia
NeMo Relay 동적 플러그인 로더, 매니페스트, Rust 네이티브 SDK, gRPC 워커 프로토콜, Python 워커 SDK, 문서, 테스트 및 릴리스 워크플로 커버리지를 유지 관리합니다.
dgx-diagnose
nvidia
일반적인 DGX Station GB300 문제 진단 — CUDA 충돌, 잘못된 GPU 타겟팅, vLLM/SGLang 컨테이너 버그, MIG 상태 문제, NVLink/Fabric Manager 오류,…