### Redshift Connection Management (Python) Source: https://context7_llms Provides examples of how to manage connections to a Redshift database using the RedshiftConnection class. It shows both context manager usage (recommended) and manual connection/disconnection, along with querying data. ```python from alx_heor.database import RedshiftConnection # Context manager (recommended) with RedshiftConnection().connect() as conn: df = conn.query("SELECT * FROM schema.table LIMIT 10") # Manual connection conn = RedshiftConnection().connect() df = conn.query("SELECT * FROM schema.table") conn.close() ``` -------------------------------- ### Get Data Source Configuration (Python) Source: https://context7_llms Retrieves the configuration details for a specified data source (e.g., 'iqvia', 'optum', 'komodo'). The configuration includes table patterns, column mappings, and lookup table names. ```python from alx_heor.config import get_source_config >>> config = get_source_config('iqvia') >>> config['columns']['patient_id'] 'pat_id' >>> config['columns']['diagnosis'] ['diag1', 'diag2', '...', 'diag12', 'diag_admit'] ``` -------------------------------- ### Get First Treatment Date using Python Source: https://context7_llms Retrieves the first treatment date for each patient from a claims DataFrame. Optionally, it can filter by a specific medication. The function returns a DataFrame containing the patient ID and their earliest treatment date. ```python def get_first_treatment_date( df_claims: pd.DataFrame, patient_id_col: str = "pat_id", date_col: str = "from_dt", medication_col: str | None = None, ) -> pd.DataFrame: # Function implementation details would go here pass # Returns DataFrame with: patient_id, first_treatment_date ``` -------------------------------- ### Get Maximum Enrollment Gap Per Patient (Python) Source: https://context7_llms The `get_max_enrollment_gap` function serves as a convenience utility to calculate the maximum enrollment gap for each patient. It takes enrollment and index DataFrames, along with configuration for months pre/post index, and returns a DataFrame with one row per patient and their `max_gap_months`. ```python def get_max_enrollment_gap( df_enrollment: pd.DataFrame, df_index: pd.DataFrame, patient_id_col: str = "pat_id", index_date_col: str = "index_date", months_pre: int = 6, months_post: int = 12, ) -> pd.DataFrame: # Function implementation details... pass ``` -------------------------------- ### Create Patient Cohort from Claims Data (Python) Source: https://context7_llms Demonstrates how to establish a Redshift connection, define cohort criteria using diagnosis codes, and retrieve a patient cohort from IQVIA claims data. It also shows how to print a summary of the cohort and access the resulting DataFrame. ```python from alx_heor import RedshiftConnection, get_cohort from alx_heor.cohort import CohortCriteria, DiagnosisCriteria conn = RedshiftConnection().connect() criteria = CohortCriteria( primary_diagnosis=DiagnosisCriteria( codes=['G700', 'G7000', 'G7001'], # gMG ICD-10 codes (no dots) min_count=2, days_apart=30, label="gMG ≥2 Dx, 30 days apart", ), min_age=18, exclude_specialties=['OPHTHAL', 'OPTOMTRY'], ) result = get_cohort( conn, source='iqvia', schema='iqvia_pharmetrics_2024q3', criteria=criteria, start_year=2015, end_year=2024, ) print(result.summary()) df_cohort = result.df_cohort ``` -------------------------------- ### Config Module: list_sources Source: https://context7_llms Lists all supported data sources available in the configuration. ```APIDOC ## Function: list_sources ### Description Returns a list of all data source names that are currently supported by the library. ### Returns - (list[str]) A list of source names, e.g., `['iqvia', 'komodo', 'optum']`. ### Usage Example ```python >>> list_sources() ['iqvia', 'komodo', 'optum'] ``` ``` -------------------------------- ### Complete Enrollment Analysis Workflow (Python) Source: https://context7_llms The `analyze_enrollment` function orchestrates the complete enrollment analysis workflow. It takes connection details, cohort data, and various parameters for gap calculation and filtering. It returns an `EnrollmentResult` dataclass summarizing the analysis. ```python def analyze_enrollment( conn: RedshiftConnection, source: str, schema: str, df_cohort: pd.DataFrame, start_year: int, end_year: int, patient_id_col: str = "pat_id", index_date_col: str = "index_date", months_pre: int = 6, months_post: int = 12, max_gap_continuous: int = 1, max_gap_censor: int = 3, study_end: str | None = None, ) -> EnrollmentResult: # Function implementation details... pass ``` -------------------------------- ### List Supported Data Sources (Python) Source: https://context7_llms Returns a list of all data sources supported by the alx_heor library. This can be used to dynamically check available data sources. ```python from alx_heor.config import list_sources >>> list_sources() ['iqvia', 'komodo', 'optum'] ``` -------------------------------- ### Config Module: get_source_config Source: https://context7_llms Retrieves configuration details for supported data sources. ```APIDOC ## Function: get_source_config ### Description Gets the configuration for a specified data source, including table patterns and column mappings. ### Parameters - **source** (str) - The name of the data source ('iqvia', 'optum', or 'komodo', case-insensitive). ### Returns - (DataSourceConfig) A TypedDict containing the data source's configuration. Keys include: - `name`: Human-readable name of the source. - `claims_table_pattern`: Pattern for claims tables (e.g., 'claims_{year}'). - `enrollment_table_pattern`: Pattern for enrollment tables (e.g., 'enroll2_{year}'). - `rx_lookup_table`: Name of the NDC lookup table. - `pr_lookup_table`: Name of the Procedure lookup table. - `columns`: A dictionary mapping common data fields (patient_id, service_date, diagnosis, etc.) to source-specific column names. - `default_claims_columns`: A list of default columns to include in claims queries. ### Usage Example ```python >>> config = get_source_config('iqvia') >>> config['columns']['patient_id'] 'pat_id' >>> config['columns']['diagnosis'] ['diag1', 'diag2', ..., 'diag12', 'diag_admit'] ``` ``` -------------------------------- ### Database Module: Utility Functions Source: https://context7_llms Utility functions for database interactions. ```APIDOC ## Function: format_in_clause ### Description Formats a list of items into a comma-separated string suitable for SQL `IN` clauses, with each item quoted. ### Parameters - **items** (list) - The list of items to format. ### Returns - (str) A formatted string for a SQL `IN` clause. ### Usage Example ```python >>> format_in_clause(['G35', 'G36', 'G37']) "'G35', 'G36', 'G37'" ``` ``` -------------------------------- ### Fetch Enrollment Data (Python) Source: https://context7_llms The `get_enrollment` function retrieves enrollment data for a given list of patient IDs within a specified date range and source. It returns a pandas DataFrame containing `patient_id` and `month_id` (in YYYYMM format). Optional columns can be specified for the returned DataFrame. ```python def get_enrollment( conn: RedshiftConnection, source: str, schema: str, patient_ids: list[str], start_year: int, end_year: int, columns: list[str] | None = None, ) -> pd.DataFrame: # Function implementation details... pass ``` -------------------------------- ### Database Module: RedshiftConnection Source: https://context7_llms Manages connections to Redshift databases, allowing for querying, data manipulation, and table management. ```APIDOC ## Class: RedshiftConnection ### Description Database connection with environment-based credentials. Supports querying, executing SQL, and managing tables. ### Methods - `__init__(self, host: str | None = None, database: str | None = None, user: str | None = None, password: str | None = None)`: Initializes the connection parameters, falling back to environment variables if not provided. - `connect(self) -> RedshiftConnection`: Establishes the database connection. - `query(self, sql: str) -> pd.DataFrame`: Executes a SQL query and returns the results as a Pandas DataFrame. - `execute(self, sql: str) -> None`: Executes a SQL statement without returning results. - `get_tables(self, schema: str, keyword: str | None = None) -> list[str]`: Retrieves a list of tables within a schema, optionally filtered by a keyword. - `get_columns(self, schema: str, table: str, keyword: str | None = None) -> list[str]`: Retrieves a list of columns for a given table, optionally filtered by a keyword. - `get_schemas(self, keyword: str | None = None) -> list[str]`: Retrieves a list of schemas, optionally filtered by a keyword. - `close(self) -> None`: Closes the database connection. - `drop_table(self, schema: str, table: str) -> None`: Drops a specified table. - `write_table(self, df: pd.DataFrame, schema: str, table: str, if_exists: str = "replace", chunksize: int = 5000) -> int`: Writes a Pandas DataFrame to a table, with options for handling existing tables and chunking. - `write_from_select(self, sql: str, schema: str, table: str, overwrite: bool = True) -> None`: Writes data to a table from the results of a SQL SELECT statement. ### Properties - `is_connected(self) -> bool`: Returns True if the connection is active, False otherwise. ### Usage Examples **Context Manager (Recommended):** ```python with RedshiftConnection().connect() as conn: df = conn.query("SELECT * FROM schema.table LIMIT 10") ``` **Manual Connection:** ```python conn = RedshiftConnection().connect() try: df = conn.query("SELECT * FROM schema.table") finally: conn.close() ``` ``` -------------------------------- ### Build SQL Query - Python Source: https://context7_llms Generates a SQL query string for retrieving claims data based on specified criteria. It allows for filtering by diagnosis codes, date ranges, and optionally by table patterns and specific columns. This function is useful for previewing SQL without direct execution. ```python def build_claims_sql( source: str, schema: str, diagnosis_codes: list[str], start_year: int, end_year: int, table_pattern: str | None = None, columns: list[str] | None = None, diagnosis_columns: list[str] | None = None, ) -> str: # Implementation details omitted for brevity ``` -------------------------------- ### Build Cohort with Full Attrition Tracking (Python) Source: https://context7_llms The `get_cohort` function builds a patient cohort with complete attrition tracking. It requires a Redshift connection, source, schema, cohort criteria, and a date range. It returns a `CohortResult` object containing the final cohort, claims data, attrition summary, and other relevant DataFrames. This is the primary function for initiating cohort analysis. ```python def get_cohort( conn: RedshiftConnection, source: str, schema: str, criteria: CohortCriteria, start_year: int, end_year: int, study_start: str | None = None, # e.g., '2015-01-01' study_end: str | None = None, # e.g., '2024-03-31' include_claims: bool = True, ) -> CohortResult: # Function implementation details... pass # Example Usage: # result = get_cohort(conn, source='iqvia', schema='...', criteria=criteria, start_year=2015, end_year=2024) # print(result.summary()) # df = result.df_cohort ``` -------------------------------- ### Query Claims by Diagnosis Codes (Python) Source: https://context7_llms Fetches claims data filtered by a list of diagnosis codes within a specified year range and from a given source and schema. Supports optional inclusion of demographic information. ```python from alx_heor.claims import get_claims # Example usage (assuming conn and other parameters are defined): # df_claims = get_claims( # conn=conn, # source='iqvia', # schema='iqvia_pharmetrics_2024q3', # diagnosis_codes=['I10'], # start_year=2020, # end_year=2022, # include_demographics=True # ) ``` -------------------------------- ### Build gMG Cohort using Python Source: https://context7_llms Constructs a cohort of patients with Generalized Myasthenia Gravis (gMG) using specified criteria. This Python snippet demonstrates building a cohort by defining diagnoses, age, specialty exclusions, and enrollment periods. It requires a Redshift connection and utilizes the `alx_heor` library. ```python from alx_heor import RedshiftConnection, get_cohort from alx_heor.cohort import CohortCriteria, DiagnosisCriteria, EnrollmentCriteria conn = RedshiftConnection().connect() criteria = CohortCriteria( primary_diagnosis=DiagnosisCriteria( codes=['G700', 'G7000', 'G7001'], min_count=2, days_apart=30, label="gMG ≥2 Dx, 30 days apart", ), min_age=18, exclude_specialties=['OPHTHAL', 'OPTOMTRY'], enrollment=EnrollmentCriteria( months_before=6, months_after=6, max_gap_months=1, ), ) result = get_cohort( conn, source='iqvia', schema='iqvia_pharmetrics_2024q3', criteria=criteria, start_year=2015, end_year=2024, study_start='2015-01-01', study_end='2023-12-31', ) print(result.summary()) df_cohort = result.df_cohort ``` -------------------------------- ### Analyze Treatment Claims using Python Source: https://context7_llms This Python code snippet retrieves treatment-related claims data for a specified cohort. It first looks up relevant medication codes (NDC and J-codes) using generic names and then fetches the corresponding claims from a database. Dependencies include database connection and medication lookup functions. ```python from alx_heor.medications import ( lookup_medications, get_treatment_claims, assign_medication_category, identify_treatment_episodes, ) # Assume conn and df_cohort are already defined # conn = RedshiftConnection().connect() # df_cohort = ... # From cohort building step # Find drug codes rx_result = lookup_medications( conn, source='iqvia', schema='iqvia_pharmetrics_2024q3', generic_names=['eculizumab', 'ravulizumab', 'efgartigimod'], ) # Get treatment claims df_rx = get_treatment_claims( conn, source='iqvia', schema='iqvia_pharmetrics_2024q3', patient_ids=df_cohort['patient_id'].tolist(), start_year=2015, end_year=2024, ndc_codes=rx_result.ndc_list, jcodes=rx_result.jcode_list, ) ``` -------------------------------- ### Execute Custom SQL Query with Python and Redshift Source: https://context7_llms Connects to a Redshift database and executes a custom SQL query to retrieve patient IDs, dates, and diagnoses from the claims table. Requires a RedshiftConnection class and pandas for data handling. ```python conn = RedshiftConnection().connect() df = conn.query(""" SELECT pat_id, from_dt, diag1, diag2 FROM schema.claims_2024 WHERE diag1 IN ('G700', 'G7000', 'G7001') LIMIT 1000 """) ``` -------------------------------- ### Identify Treatment Episodes using Python Source: https://context7_llms Groups healthcare claims into distinct treatment episodes. A new episode is initiated if the gap between consecutive claims for the same medication exceeds a specified number of days. It returns a DataFrame with episode details for each patient and medication. ```python def identify_treatment_episodes( df_claims: pd.DataFrame, patient_id_col: str = "pat_id", date_col: str = "from_dt", medication_col: str = "medication", gap_days: int = 45, ) -> pd.DataFrame: # Function implementation details would go here pass # Expected output columns: # patient_id, medication, episode_num # start_date, end_date, num_claims, duration_days ``` -------------------------------- ### Calculate Proportion of Days Covered (PDC) using Python Source: https://context7_llms Calculates the Proportion of Days Covered (PDC), an adherence metric, for patients. It considers the days supplied for medications within a defined observation window. The function returns a DataFrame with patient ID, PDC, covered days, and observation days. ```python def calculate_pdc( df_claims: pd.DataFrame, patient_id_col: str = "pat_id", date_col: str = "from_dt", days_supply_col: str | None = None, # Defaults to 30 if None observation_window: int = 365, index_date_col: str | None = None, ) -> pd.DataFrame: # Function implementation details would go here pass # Returns DataFrame with: # patient_id, pdc (0.0-1.0), covered_days, observation_days # Note: PDC >= 0.80 is generally considered adherent. ``` -------------------------------- ### Define Enrollment Criteria - Python Source: https://context7_llms A dataclass for specifying requirements for patient enrollment periods. It defines the minimum required enrollment duration before and after an index date, as well as the maximum allowed gap in coverage. This is essential for ensuring data quality and patient follow-up. ```python from dataclasses import dataclass @dataclass class EnrollmentCriteria: months_before: int = 0 # Required baseline enrollment months_after: int = 0 # Required follow-up enrollment max_gap_months: int = 1 # Maximum allowed gap label: str = "" ``` -------------------------------- ### Format List for SQL IN Clause (Python) Source: https://context7_llms A utility function to format a Python list into a comma-separated, quoted string suitable for use in a SQL IN clause. This is useful for constructing dynamic SQL queries. ```python from alx_heor.database import format_in_clause >>> format_in_clause(['G35', 'G36', 'G37']) "'G35', 'G36', 'G37'" ``` -------------------------------- ### Calculate Enrollment Gaps Relative to Index Date (Python) Source: https://context7_llms The `calculate_enrollment_gaps` function computes enrollment gaps for patients relative to an index date. It takes enrollment and index DataFrames as input, along with column names and lookback/lookforward periods in months. It returns a DataFrame with a `max_gap_months` column indicating the longest gap. ```python def calculate_enrollment_gaps( df_enrollment: pd.DataFrame, df_index: pd.DataFrame, patient_id_col: str = "pat_id", index_date_col: str = "index_date", months_pre: int = 6, months_post: int = 12, ) -> pd.DataFrame: # Function implementation details... pass ``` -------------------------------- ### Claims Module: get_claims Source: https://context7_llms Queries healthcare claims data filtered by diagnosis codes across a specified year range. ```APIDOC ## Function: get_claims ### Description Queries healthcare claims data, filtering by a list of diagnosis codes and a date range. It supports querying across multiple yearly tables using a provided table pattern and can optionally include demographic information. ### Parameters - **conn** (RedshiftConnection) - An active connection object to the database. - **source** (str) - The data source to query from ('iqvia', 'optum', 'komodo'). - **schema** (str) - The database schema containing the claims tables. - **diagnosis_codes** (list[str]) - A list of ICD codes to filter the claims by. Codes should be exact matches without dots (e.g., 'G700' instead of 'G70.0'). - **start_year** (int) - The starting year for the claims data query. - **end_year** (int) - The ending year for the claims data query. - **table_pattern** (str | None, optional) - A pattern to identify the yearly claims tables. Defaults to the source's configuration if None. - **columns** (list[str] | None, optional) - A specific list of columns to retrieve. Defaults to all columns if None. - **diagnosis_columns** (list[str] | None, optional) - A list of columns that contain diagnosis codes. Defaults to the source's configuration if None. - **include_demographics** (bool, optional) - If True, attempts to join and include demographic data (like year of birth and sex) from enrollment tables. Only supported for IQVIA source. Defaults to False. ### Returns - (pd.DataFrame) A Pandas DataFrame where each row represents a single claim matching the criteria. ### Usage Example ```python # Assuming 'conn' is an active RedshiftConnection object # and 'iqvia_schema' is the relevant schema name claims_df = get_claims( conn=conn, source='iqvia', schema='iqvia_schema', diagnosis_codes=['G700', 'G7000', 'G7001'], start_year=2020, end_year=2023, include_demographics=True ) print(claims_df.head()) ``` ``` -------------------------------- ### Filter Continuous Enrollment Based on Max Gap (Python) Source: https://context7_llms The `filter_continuous_enrollment` function filters a DataFrame of enrollment gaps to include only patients meeting a specified maximum gap criterion. It uses the `max_gap_months` column and a `max_gap` threshold. The function requires the patient ID column name. ```python def filter_continuous_enrollment( df_gaps: pd.DataFrame, max_gap: int = 1, patient_id_col: str = "pat_id", ) -> pd.DataFrame: # Function implementation details... pass ``` -------------------------------- ### Categorize Medical Data with Python Source: https://context7_llms Assigns medication categories to a DataFrame using a provided mapping. It identifies treatment episodes based on a gap in days. Requires pandas and a custom function 'assign_medication_category' and 'identify_treatment_episodes'. ```python med_map = { 'J1300': 'eculizumab', 'J1303': 'ravulizumab', 'J9332': 'efgartigimod', 'J9334': 'efgartigimod', } df_rx = assign_medication_category(df_rx, med_map) df_episodes = identify_treatment_episodes(df_rx, gap_days=45) ``` -------------------------------- ### Query Treatment Claims by NDC or J-code (Python) Source: https://context7_llms The `get_treatment_claims` function retrieves claims data for specific treatments identified by NDC or J-codes. It requires patient IDs, a date range, and the relevant codes. It returns a pandas DataFrame containing the matching claims. Optional columns can be specified. ```python def get_treatment_claims( conn: RedshiftConnection, source: str, schema: str, patient_ids: list[str], start_year: int, end_year: int, ndc_codes: list[str] | None = None, jcodes: list[str] | None = None, columns: list[str] | None = None, ) -> pd.DataFrame: # Function implementation details... pass ``` -------------------------------- ### Look Up Medications by Generic Name (Python) Source: https://context7_llms The `lookup_medications` function queries for National Drug Codes (NDC) and J-codes based on generic medication names. It accepts a list of generic names and optional keywords to exclude. It returns a `MedicationLookupResult` object containing DataFrames of codes, lists for SQL queries, and a summary. ```python def lookup_medications( conn: RedshiftConnection, source: str, schema: str, generic_names: list[str], exclude_keywords: list[str] | None = None, include_jcodes_only: bool = True, ) -> MedicationLookupResult: # Function implementation details... pass # Example Usage: # result = lookup_medications( # conn, source='iqvia', schema='...', # generic_names=['eculizumab', 'ravulizumab', 'efgartigimod'], # exclude_keywords=['HYALU'], # Exclude hyaluronidase formulations # ) # print(result.summary()) ``` -------------------------------- ### Add Demographics to Cohort - Python Source: https://context7_llms Augments a cohort DataFrame with demographic information such as age at index, year of birth, and sex. It can utilize separate claims or demographic DataFrames for this purpose. Note that for IQVIA data, demographics are typically found in the 'enroll' table. ```python import pandas as pd def add_demographics( df_index: pd.DataFrame, df_claims: pd.DataFrame | None = None, df_demographics: pd.DataFrame | None = None, source: str | None = None, patient_id_col: str | None = None, yob_col: str | None = None, sex_col: str | None = None, ) -> pd.DataFrame: # Implementation details omitted for brevity ``` -------------------------------- ### Define Cohort Criteria - Python Source: https://context7_llms A comprehensive dataclass for defining all aspects of a patient cohort. It includes criteria for inclusion and exclusion based on diagnoses, procedures, and medications, as well as demographic filters, specialty requirements, and enrollment periods. It also specifies the method for determining the index date. ```python from dataclasses import dataclass, field from typing import Literal # Assuming DiagnosisCriteria, ProcedureCriteria, MedicationCriteria, EnrollmentCriteria are defined as above @dataclass class CohortCriteria: # Inclusion primary_diagnosis: DiagnosisCriteria required_diagnoses: list[DiagnosisCriteria] = field(default_factory=list) required_procedures: list[ProcedureCriteria] = field(default_factory=list) required_medications: list[MedicationCriteria] = field(default_factory=list) # Exclusion excluded_diagnoses: list[DiagnosisCriteria] = field(default_factory=list) excluded_procedures: list[ProcedureCriteria] = field(default_factory=list) excluded_medications: list[MedicationCriteria] = field(default_factory=list) # Demographics min_age: int | None = 18 max_age: int | None = None valid_sex_only: bool = True # Specialty exclude_specialties: list[str] | None = None require_specialty_confirmation: bool = False # Enrollment enrollment: EnrollmentCriteria | None = None # Index date index_date_method: Literal["first_dx", "second_dx", "first_rx"] = "first_dx" ``` -------------------------------- ### Classify Payer Type using Python Source: https://context7_llms Classifies patients into payer types such as COMMERCIAL, MEDICARE, MEDICAID, or OTHER. It uses an enrollment DataFrame and an optional payer mapping dictionary. The function can also consider an index date for time-specific classification. ```python def classify_payer_type( df_enrollment: pd.DataFrame, patient_id_col: str = "pat_id", payer_col: str = "pay_type", index_date_col: str | None = None, payer_mapping: dict[str, list[str]] | None = None, ) -> pd.DataFrame: # Function implementation details would go here pass # Default IQVIA mapping example: # COMMERCIAL: C/S # MEDICARE: R/T/A # MEDICAID: M # OTHER: (all others) ``` -------------------------------- ### Define Diagnosis Criteria - Python Source: https://context7_llms A dataclass for defining criteria related to diagnosis codes. It allows specifying required codes, minimum counts, time windows relative to an index date, and conditions like inpatient or outpatient status. This is used for building complex cohort definitions. ```python from dataclasses import dataclass from typing import Literal @dataclass class DiagnosisCriteria: codes: list[str] # ICD codes (no dots) min_count: int = 1 # Minimum diagnoses required days_apart: int = 0 # Minimum days between first/last window_start: int | None = None # Days relative to index (negative = before) window_end: int | None = None # Days relative to index diagnosis_position: Literal["any", "primary", "admit"] = "any" require_inpatient: bool = False require_outpatient: bool = False label: str = "" # For attrition table ``` ```python # Example 1: Primary inclusion: 2+ gMG diagnoses 30 days apart DiagnosisCriteria( codes=["G700", "G7000", "G7001"], min_count=2, days_apart=30, label="gMG ≥2 Dx, 30 days apart", ) ``` ```python # Example 2: Baseline exclusion: malignancy in year before index DiagnosisCriteria( codes=["C00", "C00"], window_start=-365, window_end=-1, label="Malignancy in baseline", ) ``` -------------------------------- ### Assign Medication Category using Python Source: https://context7_llms Adds a medication category column to a DataFrame based on NDC or J-code mapping. It takes a pandas DataFrame and a dictionary mapping codes to medication names as input. The function allows specifying the columns for NDC, procedure code, and the output category. ```python def assign_medication_category( df_claims: pd.DataFrame, medication_map: dict[str, str], # {code: medication_name} ndc_column: str = "ndc", proc_column: str = "proc1", category_column: str = "medication", ) -> pd.DataFrame: # Function implementation details would go here pass # Example Usage: med_map = {'J1300': 'eculizumab', 'J9332': 'efgartigimod', 'J1303': 'ravulizumab'} df = assign_medication_category(df_claims, med_map) ``` -------------------------------- ### Identify Index Dates - Python Source: https://context7_llms Identifies 'index dates' from a DataFrame of healthcare claims. It can filter patients based on the minimum number of diagnoses and the time span between diagnoses. This function is crucial for defining patient cohorts based on specific clinical events. ```python import pandas as pd def get_index_dates( df_claims: pd.DataFrame, source: str | None = None, patient_id_col: str | None = None, date_col: str | None = None, min_diagnosis_count: int = 1, days_apart: int = 30, ) -> pd.DataFrame: # Implementation details omitted for brevity ``` -------------------------------- ### Define Procedure Criteria - Python Source: https://context7_llms A dataclass for specifying criteria related to medical procedures, identified by CPT/HCPCS codes. It allows setting minimum counts and time windows relative to an index date. This is useful for defining cohorts based on specific interventions. ```python from dataclasses import dataclass @dataclass class ProcedureCriteria: codes: list[str] # CPT/HCPCS codes min_count: int = 1 window_start: int | None = None window_end: int | None = None label: str = "" ``` -------------------------------- ### Calculate Censor Dates for Survival Analysis (Python) Source: https://context7_llms The `get_censor_dates` function calculates censoring dates for survival analysis. It determines censoring based on either the study end date or a maximum gap in enrollment, returning a DataFrame with `censor_date`, `is_censored_by_gap`, and `days_to_censor`. ```python def get_censor_dates( df_gaps: pd.DataFrame, study_end: str, # e.g., '2024-03-31' max_gap_for_censor: int = 3, patient_id_col: str = "pat_id", index_date_col: str = "index_date", ) -> pd.DataFrame: # Function implementation details... pass ``` -------------------------------- ### Filter Demographics - Python Source: https://context7_llms Filters a DataFrame based on age and sex criteria. It allows specifying minimum and maximum age, and whether to include only valid sex entries. The function returns a non-destructive copy of the DataFrame, ensuring the original data remains unchanged. ```python import pandas as pd def filter_demographics( df: pd.DataFrame, min_age: int | None = None, max_age: int | None = None, valid_sex_only: bool = True, age_col: str = "age_at_index", sex_col: str = "sex", ) -> pd.DataFrame: # Implementation details omitted for brevity ``` -------------------------------- ### Define Medication Criteria - Python Source: https://context7_llms A dataclass for defining criteria based on medication usage, identified by generic names, NDC codes, or procedure codes (J-codes). It allows for minimum counts and time windows relative to an index date. At least one type of code is required. ```python from dataclasses import dataclass @dataclass class MedicationCriteria: generic_names: list[str] | None = None # e.g., ['eculizumab', 'ravulizumab'] ndc_codes: list[str] | None = None procedure_codes: list[str] | None = None # J-codes min_count: int = 1 window_start: int | None = None window_end: int | None = None label: str = "" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.