### Install hccinfhir for Development Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Clone the repository and install the hccinfhir package in development mode. This is useful for contributing to the project. ```bash git clone https://github.com/mimilabs/hccinfhir.git cd hccinfhir pip install -e . ``` -------------------------------- ### Install Package in Development Mode Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Install the package in development mode to enable local modifications and testing. ```bash # Install in development mode pip install -e . ``` -------------------------------- ### Install HCCInFHIR in Development Mode Source: https://github.com/mimilabs/hccinfhir/blob/main/CLAUDE.md Installs the package in development mode, allowing for immediate use and testing of local changes. Ensure the virtual environment is activated first. ```bash pip install -e . ``` -------------------------------- ### Install hccinfhir Library Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Install the HCCInFHIR library using pip. Ensure you are using Python 3.9 or later. ```bash pip install hccinfhir ``` -------------------------------- ### Activate Virtual Environment Source: https://github.com/mimilabs/hccinfhir/blob/main/CLAUDE.md Activates the virtual environment for development. This is the first step before installing the package or running tests. ```bash hatch shell ``` -------------------------------- ### Initialize HCCInFHIR with Bundled Data Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Use this option when you want to leverage the default CMS reference files included with the package. No additional file setup is required. ```python from hccinfhir import HCCInFHIR # Option 1: Use bundled data (default - no setup needed) processor = HCCInFHIR( model_name="CMS-HCC Model V28", dx_cc_mapping_filename="ra_dx_to_cc_2026.csv" # ✅ Loads from package ) ``` -------------------------------- ### Run All Tests Source: https://github.com/mimilabs/hccinfhir/blob/main/CLAUDE.md Executes all tests within the project to ensure code integrity and functionality. This command should be run after installing the package. ```bash pytest tests/* ``` -------------------------------- ### Get Sample X12 Data Source: https://github.com/mimilabs/hccinfhir/blob/main/CLAUDE.md Retrieves sample X12 data, including 837 (professional claim) and 834 (enrollment) formats. Specify the case index for the desired sample. ```python from hccinfhir import get_837_sample, get_834_sample # Get X12 837 samples x12_text = get_837_sample(0) # Professional claim (cases 0-12) # Get X12 834 sample x12_834 = get_834_sample(1) # Enrollment data (case 1) ``` -------------------------------- ### Custom File Format: RAF Coefficients Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Example CSV format for the RAF coefficients file, containing demographic, HCC, and interaction coefficients for risk adjustment. ```csv coefficient,value,model_domain,model_version cna_f70_74,0.395,CMS-HCC,V28 cna_hcc19,0.302,CMS-HCC,V28 ``` -------------------------------- ### Parse 820 Payment Data and Print Details Source: https://github.com/mimilabs/hccinfhir/blob/main/CLAUDE.md Basic usage example to extract and print payer/payee names, total amount, EFT details, and member-specific remittance entries from an 820 payment. ```python from hccinfhir import get_820_sample from hccinfhir.extractor_820 import extract_payment_820 payments = extract_payment_820(get_820_sample(1)) # one PaymentData per ST*820 payment = payments[0] print(payment.payer_name, "→", payment.payee_name) print(f"Total: ${payment.total_amount:,.2f} EFT: {payment.check_number}") for member in payment.members: for entry in member.remittance_entries: print(f" {member.member_id} {entry.coverage_period_start}..{entry.coverage_period_end} " f"${entry.payment_amount:,.2f} aid={entry.aid_code}/{entry.plan_type} " f"{entry.description or ''}") ``` -------------------------------- ### Process CMS Encounter Data Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Process 837 encounter data using the HCCInFHIR processor. This example demonstrates loading data, extracting service-level details, defining demographics, and calculating the risk score. ```python from hccinfhir import HCCInFHIR, Demographics from hccinfhir.extractor import extract_sld # Step 1: Configure processor # All data file parameters are optional and default to the latest 2026 valuesets processor = HCCInFHIR( model_name="CMS-HCC Model V28", filter_claims=True, # Apply CMS filtering rules # Optional: Override with custom data files (omit to use bundled 2026 defaults) # proc_filtering_filename="ra_eligible_cpt_hcpcs_2026.csv", # CPT/HCPCS codes # dx_cc_mapping_filename="ra_dx_to_cc_2026.csv", # ICD-10 to HCC # hierarchies_filename="ra_hierarchies_2026.csv", # HCC hierarchies # is_chronic_filename="hcc_is_chronic.csv", # Chronic flags # coefficients_filename="ra_coefficients_2026.csv" # RAF coefficients ) # Step 2: Load 837 data with open("encounter_data.txt", "r") as f: raw_837_data = f.read() # Step 3: Extract service-level data service_data = extract_sld(raw_837_data, format="837") # Step 4: Define beneficiary demographics demographics = Demographics( age=72, sex="M", dual_elgbl_cd="00", # Non-dual eligible orec="0", # Original reason for entitlement crec="0", # Current reason for entitlement orig_disabled=False, new_enrollee=False, esrd=False ) # Step 5: Calculate risk score result = processor.run_from_service_data(service_data, demographics) # Step 6: Review results print(f"Risk Score: {result.risk_score:.3f}") print(f"Active HCCs: {result.hcc_list}") print(f"Disease Interactions: {result.interactions}") print(f"Diagnosis Mappings:") for cc, dx_codes in result.cc_to_dx.items(): print(f" HCC {cc}: {', '.join(dx_codes)}") # Export for CMS submission encounter_summary = { "beneficiary_id": "12345", "risk_score": result.risk_score, "hcc_list": result.hcc_list, "model": "V28", "payment_year": 2026 } ``` -------------------------------- ### Get Sample 834 Data Source: https://github.com/mimilabs/hccinfhir/blob/main/CLAUDE.md Retrieves a specific sample 834 file content using the get_834_sample function. This is useful for testing and understanding different enrollment scenarios. ```python from hccinfhir import get_834_sample # Get sample 834 content_834 = get_834_sample(1) enrollments = extract_enrollment_834(content_834) ``` -------------------------------- ### Get Sample FHIR EOB Data Source: https://github.com/mimilabs/hccinfhir/blob/main/CLAUDE.md Fetches sample FHIR Explanation of Benefits (EOB) data. Use `get_eob_sample` for a single record or `get_eob_sample_list` for multiple records. ```python from hccinfhir import get_eob_sample, get_eob_sample_list # Get FHIR EOB samples eob = get_eob_sample(1) # Individual sample (cases 1, 2, or 3) eob_list = get_eob_sample_list(limit=200) # Up to 200 samples ``` -------------------------------- ### Run All Tests Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Execute the entire test suite for the project. ```bash # Run all tests (238 tests) pytest tests/ ``` -------------------------------- ### Development Environment: Use Bundled Files Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Configure the processor to use bundled files, suitable for development and testing environments where custom data files are not yet prepared. ```python # Use bundled files for testing processor = HCCInFHIR(model_name="CMS-HCC Model V28") ``` -------------------------------- ### Get Demographic Coefficients Source: https://github.com/mimilabs/hccinfhir/blob/main/CLAUDE.md Retrieves demographic coefficients for a specific HCC model. Ensure the correct model name and demographic details are provided. ```python from hccinfhir.model_demographics import get_demographic_coefficients coeffs = get_demographic_coefficients( age=67, sex="F", dual_elgbl_cd="N", model_name="CMS-HCC Model V28" ) ``` -------------------------------- ### Initialize HCCInFHIR with Mixed File Sources Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Combine bundled default files with custom files specified by relative or absolute paths. This allows overriding specific configurations while using defaults for others. ```python # Option 4: Mix bundled and custom files processor = HCCInFHIR( model_name="CMS-HCC Model V28", dx_cc_mapping_filename="ra_dx_to_cc_2026.csv", # Bundled default coefficients_filename="custom_coefficients.csv" # Custom from current dir ) ``` -------------------------------- ### Custom File Format: HCC Hierarchies Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Example CSV format for the HCC hierarchies file, defining parent-child relationships between HCCs to suppress child HCCs. ```csv cc_parent,cc_child,model_domain,model_version,model_fullname 17,18,CMS-HCC,V28,CMS-HCC Model V28 17,19,CMS-HCC,V28,CMS-HCC Model V28 ``` -------------------------------- ### Initialize HCCInFHIR with Absolute Path Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Use an absolute path for production deployments to ensure the library accesses data files from a fixed, known location on the filesystem. ```python # Option 3: Absolute path (production deployments) processor = HCCInFHIR( model_name="CMS-HCC Model V28", dx_cc_mapping_filename="/var/data/cms/dx_mapping_2026.csv" # ✅ Absolute ) ``` -------------------------------- ### Custom File Format: Procedure Filtering Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Example CSV format for the procedure filtering data file, used for CMS filtering based on CPT/HCPCS codes. ```csv cpt_hcpcs_code 99213 99214 99215 ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Execute tests and generate an HTML report of code coverage. ```bash # Run with coverage pytest tests/ --cov=hccinfhir --cov-report=html ``` -------------------------------- ### Initialize HCCInFHIR with Custom Data Files Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Instantiate the HCCInFHIR processor, overriding default CMS reference data files with custom CSV files. Supports absolute paths, relative paths, or bundled filenames for all five data files. ```python processor = HCCInFHIR( model_name="CMS-HCC Model V28", filter_claims=True, # All files support absolute paths, relative paths, or bundled filenames # See "Custom File Path Resolution" in Advanced Features for details # 1. CPT/HCPCS Procedure Codes (for CMS filtering) proc_filtering_filename="ra_eligible_cpt_hcpcs_2026.csv", # 2. Diagnosis to HCC Mapping (ICD-10 → HCC) dx_cc_mapping_filename="ra_dx_to_cc_2026.csv", # 3. HCC Hierarchies (parent HCCs suppress child HCCs) hierarchies_filename="ra_hierarchies_2026.csv", # 4. Chronic Condition Flags is_chronic_filename="hcc_is_chronic.csv", # 5. RAF Coefficients (demographic + HCC + interaction coefficients) coefficients_filename="ra_coefficients_2026.csv" ) ``` -------------------------------- ### Custom File Format: Chronic Condition Flags Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Example CSV format for the chronic condition flags file, indicating whether an HCC represents a chronic condition. ```csv hcc,is_chronic,model_version,model_domain 1,True,V28,CMS-HCC 2,False,V28,CMS-HCC ``` -------------------------------- ### Initialize HCCInFHIR with Relative Path Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Specify a relative path to load custom data files from the current working directory. Ensure the file exists at the specified relative location. ```python # Option 2: Relative path from current directory # Assumes: ./custom_data/my_dx_mapping.csv exists processor = HCCInFHIR( model_name="CMS-HCC Model V28", dx_cc_mapping_filename="custom_data/my_dx_mapping.csv" # ✅ ./custom_data/ ) ``` -------------------------------- ### Basic Usage of 834 Enrollment Parser Source: https://github.com/mimilabs/hccinfhir/blob/main/CLAUDE.md Shows how to load an 834 file, parse enrollment data using `extract_enrollment_834`, and iterate through enrollments to print key member details like MBI, Medicaid ID, and dual status. It also demonstrates converting enrollment data to Demographics objects for RAF calculation. ```python from hccinfhir.extractor_834 import extract_enrollment_834, enrollment_to_demographics # Load 834 file with open('dhcs_834_file.txt', 'r') as f: content = f.read() # Parse enrollments enrollments = extract_enrollment_834(content) # Process each member for enrollment in enrollments: print(f"Member: {enrollment.member_id}") print(f"MBI: {enrollment.mbi}") print(f"Medicaid ID: {enrollment.medicaid_id}") print(f"Dual Status: {enrollment.dual_elgbl_cd}") print(f"Full Benefit Dual: {enrollment.is_full_benefit_dual}") print(f"Partial Benefit Dual: {enrollment.is_partial_benefit_dual}") # Convert to Demographics for RAF calculation demographics = enrollment_to_demographics(enrollment) ``` -------------------------------- ### Custom File Format: Diagnosis to HCC Mapping Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Example CSV format for the diagnosis to HCC mapping file, linking ICD-10 codes to HCCs for a specific model. ```csv diagnosis_code,cc,model_name E119,38,CMS-HCC Model V28 I10,226,CMS-HCC Model V28 ``` -------------------------------- ### Activate Virtual Environment Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Activate the Python virtual environment before running any commands. ```bash # Activate virtual environment hatch shell ``` -------------------------------- ### Override Coefficient Prefix for Institutionalized Patient Source: https://github.com/mimilabs/hccinfhir/blob/main/CLAUDE.md Use prefix_override to apply institutionalized coefficients when a patient's status is not correctly detected from demographics. This example shows overriding for a patient who should be flagged as LTI. ```python from hccinfhir import HCCInFHIR, Demographics # Example 2: Institutionalized patient not properly flagged processor = HCCInFHIR(model_name="CMS-HCC Model V28") demographics = Demographics(age=78, sex="M") # Should be LTI diagnosis_codes = ["F03.90", "I48.91", "N18.4"] # Override to use institutionalized coefficients result = processor.calculate_from_diagnosis( diagnosis_codes, demographics, prefix_override='INS_' ) ``` -------------------------------- ### Initialize HCCInFHIR Processor Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Instantiate the main HCCInFHIR class. Customize processing by providing filenames for model data and optionally enabling claim filtering. ```python HCCInFHIR( filter_claims: bool = True, model_name: ModelName = "CMS-HCC Model V28", proc_filtering_filename: str = "ra_eligible_cpt_hcpcs_2026.csv", dx_cc_mapping_filename: str = "ra_dx_to_cc_2026.csv", hierarchies_filename: str = "ra_hierarchies_2026.csv", is_chronic_filename: str = "hcc_is_chronic.csv", coefficients_filename: str = "ra_coefficients_2026.csv" ) ``` -------------------------------- ### Error Handling for File Not Found Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Demonstrates how to catch `FileNotFoundError` when initializing HCCInFHIR with a non-existent data file. The error message will indicate all checked locations. ```python from hccinfhir import HCCInFHIR try: processor = HCCInFHIR( model_name="CMS-HCC Model V28", dx_cc_mapping_filename="nonexistent.csv" ) except FileNotFoundError as e: print(f"File not found: {e}") # Error shows all locations checked: # - Current directory: /path/to/cwd # - Package data: hccinfhir.data ``` -------------------------------- ### Run Specific Test File Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Execute tests from a particular file, with verbose output. ```bash # Run specific test file pytest tests/test_model_calculate.py -v ``` -------------------------------- ### Override Coefficient Prefix for ESRD Patient Source: https://github.com/mimilabs/hccinfhir/blob/main/CLAUDE.md Use prefix_override to force ESRD dialysis coefficients when demographic data might be incorrect. This example demonstrates overriding for a patient with potentially erroneous orec/crec codes. ```python from hccinfhir import HCCInFHIR, Demographics # Example 1: ESRD patient with bad orec/crec data processor = HCCInFHIR(model_name="CMS-HCC ESRD Model V24") demographics = Demographics(age=65, sex="F", orec="0", crec="0") # Wrong codes diagnosis_codes = ["N18.6", "E11.22", "I12.0"] # Override to force ESRD dialysis coefficients result = processor.calculate_from_diagnosis( diagnosis_codes, demographics, prefix_override='DI_' ) ``` -------------------------------- ### FastAPI Endpoint for Risk Calculation Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md An example of a FastAPI POST endpoint that accepts diagnosis codes and demographics, calculates risk scores using HCCInFHIR, and returns the result in a JSON-serializable dictionary format. Ensures automatic JSON serialization for API responses. ```python from fastapi import FastAPI from hccinfhir import Demographics, HCCInFHIR processor = HCCInFHIR(model_name="CMS-HCC Model V28") app = FastAPI() @app.post("/calculate") def calculate_risk(diagnosis_codes: list, demographics: dict): demo = Demographics(**demographics) result = processor.calculate_from_diagnosis(diagnosis_codes, demo) return result.model_dump(mode='json') # Automatic JSON serialization ``` -------------------------------- ### Initialize HCCInFHIR Processor Source: https://github.com/mimilabs/hccinfhir/blob/main/CLAUDE.md Initializes the main processor class with configuration for filtering and HCC model. ```python from hccinfhir import HCCInFHIR, Demographics # Initialize processor processor = HCCInFHIR( filter_claims=True, # Apply CMS filtering rules model_name="CMS-HCC Model V28", # HCC model to use proc_filtering_filename="ra_eligible_cpt_hcpcs_2026.csv", # CPT/HCPCS filtering dx_cc_mapping_filename="ra_dx_to_cc_2026.csv" # Diagnosis mapping ) ``` -------------------------------- ### HCCInFHIR Initialization Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Initializes the main HCCInFHIR processor class. Allows configuration of filtering, model, and various mapping/coefficient files. ```APIDOC ## Class HCCInFHIR ### Description Main processor class for HCC risk adjustment calculations. ### Initialization ```python HCCInFHIR( filter_claims: bool = True, model_name: ModelName = "CMS-HCC Model V28", proc_filtering_filename: str = "ra_eligible_cpt_hcpcs_2026.csv", dx_cc_mapping_filename: str = "ra_dx_to_cc_2026.csv", hierarchies_filename: str = "ra_hierarchies_2026.csv", is_chronic_filename: str = "hcc_is_chronic.csv", coefficients_filename: str = "ra_coefficients_2026.csv" ) ``` ### Parameters #### Initialization Parameters - **filter_claims** (bool) - Optional - Whether to filter claims. - **model_name** (ModelName) - Optional - The HCC model to use (default: "CMS-HCC Model V28"). - **proc_filtering_filename** (str) - Optional - Filename for procedure filtering. - **dx_cc_mapping_filename** (str) - Optional - Filename for diagnosis to CC mapping. - **hierarchies_filename** (str) - Optional - Filename for hierarchy data. - **is_chronic_filename** (str) - Optional - Filename for chronic condition data. - **coefficients_filename** (str) - Optional - Filename for coefficients. ``` -------------------------------- ### Calculate HCC Risk Scores with Databricks UDF Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md This pandas UDF calculates HCC risk scores from patient data including age, sex, and diagnosis codes. It processes data in batches and handles potential errors by returning null values. Ensure the 'hccinfhir' library is installed on all cluster nodes. ```python from pyspark.sql import SparkSession from pyspark.sql.types import StructType, StructField, FloatType, ArrayType, StringType from pyspark.sql import functions as F from pyspark.sql.functions import pandas_udf import pandas as pd from hccinfhir import HCCInFHIR, Demographics # Define the return schema hcc_schema = StructType([ StructField("risk_score", FloatType(), True), StructField("risk_score_demographics", FloatType(), True), StructField("risk_score_chronic_only", FloatType(), True), StructField("risk_score_hcc", FloatType(), True), StructField("hcc_list", ArrayType(StringType()), True) ]) # Initialize processor (will be serialized to each executor) hcc_processor = HCCInFHIR(model_name="CMS-HCC Model V28") # Create the pandas UDF @pandas_udf(hcc_schema) def calculate_hcc( age_series: pd.Series, sex_series: pd.Series, diagnosis_series: pd.Series ) -> pd.DataFrame: results = [] for age, sex, diagnosis_codes in zip(age_series, sex_series, diagnosis_series): try: demographics = Demographics(age=int(age), sex=sex) # diagnosis_codes can be passed directly - accepts any iterable including numpy arrays result = hcc_processor.calculate_from_diagnosis(diagnosis_codes, demographics) results.append({ 'risk_score': float(result.risk_score), 'risk_score_demographics': float(result.risk_score_demographics), 'risk_score_chronic_only': float(result.risk_score_chronic_only), 'risk_score_hcc': float(result.risk_score_hcc), 'hcc_list': result.hcc_list }) except Exception as e: # Log error and return nulls for failed rows print(f"ERROR processing row: {e}") results.append({ 'risk_score': None, 'risk_score_demographics': None, 'risk_score_chronic_only': None, 'risk_score_hcc': None, 'hcc_list': None }) return pd.DataFrame(results) # Apply the UDF to your DataFrame # Assumes df has columns: age, patient_gender, diagnosis_codes (array of strings) df = df.withColumn( "hcc_results", calculate_hcc( F.col("age"), F.col("patient_gender"), F.col("diagnosis_codes") ) ) # Expand the struct into separate columns df = df.select( "*", F.col("hcc_results.risk_score").alias("risk_score"), F.col("hcc_results.risk_score_demographics").alias("risk_score_demographics"), F.col("hcc_results.risk_score_chronic_only").alias("risk_score_chronic_only"), F.col("hcc_results.risk_score_hcc").alias("risk_score_hcc"), F.col("hcc_results.hcc_list").alias("hcc_list") ).drop("hcc_results") ``` -------------------------------- ### Calculate HCC Risk Scores with Extended Demographics UDF Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md This pandas UDF extends the HCC risk score calculation to include additional demographic parameters like dual eligibility status. It follows a similar error handling pattern as the basic UDF, returning nulls for failed rows. Ensure 'hccinfhir' is installed on all cluster nodes. ```python # Include additional demographic parameters @pandas_udf(hcc_schema) def calculate_hcc_full( age_series: pd.Series, sex_series: pd.Series, dual_status_series: pd.Series, diagnosis_series: pd.Series ) -> pd.DataFrame: results = [] for age, sex, dual_status, diagnosis_codes in zip( age_series, sex_series, dual_status_series, diagnosis_series ): try: demographics = Demographics( age=int(age), sex=sex, dual_elgbl_cd=dual_status if dual_status else "00" ) result = hcc_processor.calculate_from_diagnosis(diagnosis_codes, demographics) results.append({ 'risk_score': float(result.risk_score), 'risk_score_demographics': float(result.risk_score_demographics), 'risk_score_chronic_only': float(result.risk_score_chronic_only), 'risk_score_hcc': float(result.risk_score_hcc), 'hcc_list': result.hcc_list }) except Exception as e: results.append({ 'risk_score': None, 'risk_score_demographics': None, 'risk_score_chronic_only': None, 'risk_score_hcc': None, 'hcc_list': None }) return pd.DataFrame(results) ``` -------------------------------- ### Initialize Demographics Object Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Create a Demographics object with required and optional fields for beneficiary information. Key fields like age, sex, and dual eligibility are critical for payment accuracy. ```python from hccinfhir import Demographics demographics = Demographics( # Required fields age=67, # Age in years sex="F", # "M" or "F" (also accepts "1" or "2") # Dual eligibility (critical for payment accuracy) dual_elgbl_cd="00", # "00"=Non-dual, "01"=Partial, "02"=Full # "03"=Partial, "04"=Full, "05"=QDWI # "06"=QI, "08"=Other full benefit dual # Medicare entitlement orec="0", # Original reason for entitlement # "0"=Old age, "1"=Disability, "2"=ESRD, "3"=Both crec="0", # Current reason for entitlement # Status flags orig_disabled=False, # Original disability (affects category) new_enrollee=False, # New to Medicare (<12 months) esrd=False, # End-Stage Renal Disease (auto-detected from orec/crec) # Optional fields snp=False, # Special Needs Plan low_income=False, # Low-income subsidy (Part D) lti=False, # Long-term institutionalized graft_months=None, # Months since kidney transplant (ESRD models) fbd=False, # Full benefit dual (auto-set from dual_elgbl_cd) pbd=False, # Partial benefit dual (auto-set) # Auto-calculated (can override) category="CNA" # Beneficiary category (auto-calculated if omitted) ) ``` -------------------------------- ### Build HCCInFHIR Package Source: https://github.com/mimilabs/hccinfhir/blob/main/CLAUDE.md Builds the distributable package for the HCCInFHIR library. This command is used before publishing or for local distribution. ```bash hatch build ``` -------------------------------- ### Import HCCInFHIR Utility Functions Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Import various utility functions for accessing sample data, extracting information from FHIR resources, and parsing enrollment files. ```python from hccinfhir import ( get_eob_sample, get_837_sample, get_834_sample, get_eob_sample_list, get_837_sample_list, list_available_samples, ) ``` ```python from hccinfhir.extractor import ( extract_sld, extract_sld_list, ) ``` ```python from hccinfhir.extractor_834 import ( extract_enrollment_834, enrollment_to_demographics, is_losing_medicaid, medicaid_status_summary, ) ``` ```python from hccinfhir.filter import apply_filter ``` ```python from hccinfhir.model_calculate import calculate_raf ``` -------------------------------- ### Calculate Risk Score and HCC List with hccpy Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md This snippet demonstrates how to initialize HCCEngine and calculate risk scores and HCC lists using diagnosis codes with the hccpy library. ```python from hccpy.hcc import HCCEngine he = HCCEngine("28") rp = he.profile(["E1169", "I5030", "I509", "I211", "I209", "R05"], age=70, sex="M") print(rp["risk_score"]) print(rp["hcc_lst"]) ``` -------------------------------- ### HCCInFHIR Integration with 834 and 837 Data Source: https://github.com/mimilabs/hccinfhir/blob/main/CLAUDE.md Demonstrates parsing enrollment data from an 834 file and claims data from an 837 file, then using the HCCInFHIR processor to calculate the RAF score for a member. ```python from hccinfhir import HCCInFHIR from hccinfhir.extractor_834 import extract_enrollment_834, enrollment_to_demographics from hccinfhir.extractor_837 import extract_sld_837 # Parse enrollment data enrollments_834 = extract_enrollment_834(content_834) # Parse claims data service_data_837 = extract_sld_837(content_837) # Match member and calculate RAF processor = HCCInFHIR() for enrollment in enrollments_834: # Get demographics from 834 demographics = enrollment_to_demographics(enrollment) # Filter claims for this member member_claims = [sld for sld in service_data_837 if sld.patient_id == enrollment.member_id] # Calculate RAF score result = processor.run_from_service_data(member_claims, demographics) print(f"Member: {enrollment.member_id}") print(f"Dual Status: {enrollment.dual_elgbl_cd}") print(f"RAF Score: {result.risk_score}") ``` -------------------------------- ### Production Scenario: Centralized Data Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Configure the processor to use custom files located in a centralized network path for production environments. This ensures all data files are managed in a single, accessible location. ```python # All custom files in shared network location data_path = "/mnt/shared/cms_data/2026" processor = HCCInFHIR( model_name="CMS-HCC Model V28", proc_filtering_filename=f"{data_path}/cpt_hcpcs.csv", dx_cc_mapping_filename=f"{data_path}/dx_to_cc.csv", hierarchies_filename=f"{data_path}/hierarchies.csv", is_chronic_filename=f"{data_path}/chronic_flags.csv", coefficients_filename=f"{data_path}/coefficients.csv" ) ``` -------------------------------- ### Process X12 834 Enrollment for Dual Eligibility and RAF Calculation Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md This script parses an X12 834 enrollment file, processes each member's enrollment data, checks for Medicaid coverage loss, summarizes Medicaid status, and calculates the RAF score using the HCCInFHIR library. It requires the enrollment data to be in a file named 'enrollment_834.txt'. ```python from hccinfhir import HCCInFHIR, Demographics from hccinfhir.extractor_834 import ( extract_enrollment_834, enrollment_to_demographics, is_losing_medicaid, medicaid_status_summary ) # Step 1: Parse X12 834 enrollment file with open("enrollment_834.txt", "r") as f: x12_834_data = f.read() enrollments = extract_enrollment_834(x12_834_data) # Step 2: Process each member processor = HCCInFHIR(model_name="CMS-HCC Model V28") for enrollment in enrollments: # Convert enrollment to Demographics for RAF calculation demographics = enrollment_to_demographics(enrollment) print(f"\n=== Member: {enrollment.member_id} ===") print(f"MBI: {enrollment.mbi}") print(f"Medicaid ID: {enrollment.medicaid_id}") print(f"Dual Status: {enrollment.dual_elgbl_cd}") print(f"Full Benefit Dual: {enrollment.is_full_benefit_dual}") print(f"Partial Benefit Dual: {enrollment.is_partial_benefit_dual}") # Step 3: Check for Medicaid coverage loss (critical for RAF projections) if is_losing_medicaid(enrollment, within_days=90): print(f"⚠️ ALERT: Member losing Medicaid coverage!") print(f" Coverage ends: {enrollment.coverage_end_date}") print(f" Expected RAF impact: -30% to -50%") # Step 4: Get comprehensive Medicaid status status = medicaid_status_summary(enrollment) print(f"\nMedicaid Status Summary:") print(f" Has Medicare: {status['has_medicare']}") print(f" Has Medicaid: {status['has_medicaid']}") print(f" Dual Status Code: {status['dual_status']}") print(f" Full Benefit Dual: {status['is_full_benefit_dual']}") print(f" Partial Benefit Dual: {status['is_partial_benefit_dual']}") print(f" Coverage End: {status['coverage_end_date']}") # Step 5: Calculate RAF with accurate dual status diagnosis_codes = ["E11.9", "I10", "N18.3"] # From claims result = processor.calculate_from_diagnosis(diagnosis_codes, demographics) print(f"\nRAF Score: {result.risk_score:.3f}") ``` -------------------------------- ### Publish HCCInFHIR to PyPI Source: https://github.com/mimilabs/hccinfhir/blob/main/CLAUDE.md Publishes the built HCCInFHIR package to the Python Package Index (PyPI). This command is restricted to maintainers only and requires the package to be built first. ```bash hatch publish ``` -------------------------------- ### Process Sample EOB with Demographics Source: https://github.com/mimilabs/hccinfhir/blob/main/CLAUDE.md Processes a single sample EOB record using the HCCInFHIR processor with provided demographics. Note that a single EOB must be wrapped in a list. ```python from hccinfhir import HCCInFHIR from hccinfhir.demographics import Demographics # Process sample data processor = HCCInFHIR() demographics = Demographics(age=67, sex="F") result = processor.run([eob], demographics) # Note: wrap single EOB in list ``` -------------------------------- ### Research Scenario: Custom Coefficients Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Customize specific data files, such as coefficients, while retaining bundled defaults for other mappings. This is useful for research requiring adjusted parameters. ```python # Keep standard mappings, customize coefficients # File: ./research/adjusted_coefficients.csv processor = HCCInFHIR( model_name="CMS-HCC Model V28", coefficients_filename="research/adjusted_coefficients.csv" ) ``` -------------------------------- ### Docker Scenario: Mounted Volume Data Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Configure the processor to access data files from a mounted volume within a Docker container. This allows data to persist and be managed outside the container. ```python # Files mounted at /app/data processor = HCCInFHIR( model_name="CMS-HCC Model V28", dx_cc_mapping_filename="/app/data/dx_to_cc_custom.csv", coefficients_filename="/app/data/coefficients_custom.csv" # Other files use bundled defaults ) ``` -------------------------------- ### Calculate Risk Score and HCC List with HCCInFHIR Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md This snippet shows how to initialize HCCInFHIR and calculate risk scores and HCC lists using diagnosis codes with the HCCInFHIR library. ```python from hccinfhir import HCCInFHIR processor = HCCInFHIR(model_name="CMS-HCC Model V28") result = processor.calculate_from_diagnosis(["E1169", "I5030", "I509", "I211", "I209", "R05"], age=70, sex="M") print(result.risk_score) print(result.hcc_list) ``` -------------------------------- ### Verify Dual Eligibility Rates in 820 vs 834 Data Source: https://github.com/mimilabs/hccinfhir/blob/main/README.md Cross-references dual eligibility codes from 834 enrollment data with aid codes in 820 remittance entries. It flags mismatches where a member was paid at the wrong rate. ```python from hccinfhir.extractor_834 import extract_enrollment_834 from hccinfhir import get_834_sample dual_map = {e.member_id: e.dual_elgbl_cd for e in extract_enrollment_834(get_834_sample(1))} DUAL_AID_CODES = {"1H", "60", "10", "16", "17", "6H", "20"} for member in payment.members: dual_cd = dual_map.get(member.member_id) if dual_cd is None: continue for entry in member.remittance_entries: paid_as_dual = entry.aid_code in DUAL_AID_CODES enrolled_as_dual = dual_cd not in ("00", "NA", None) if paid_as_dual != enrolled_as_dual: print(f"Rate mismatch {member.member_id}: " f"paid as {'dual' if paid_as_dual else 'non-dual'} " f"but enrolled dual_elgbl_cd={dual_cd}") ``` -------------------------------- ### Extract Payment Data from Sample 820 Source: https://github.com/mimilabs/hccinfhir/blob/main/CLAUDE.md Extracts payment data from a specific sample X12 820 file, particularly useful for scenarios involving prior-period adjustments. ```python from hccinfhir import get_820_sample from hccinfhir.extractor_820 import extract_payment_820 payment = extract_payment_820(get_820_sample(2))[0] # sample with ADX adjustments ```