keybindings-help debug frontend-design sc:analyze sc:build sc:cleanup sc:design sc:document sc:estimate sc:explain sc:git sc:implement sc:improve sc:index sc:load sc:spawn sc:task sc:test sc:troubleshoot sc:workflow compact context cost init pr-comments release-notes review security-review insights

Bash general-purpose statusline-setup Explore Plan code-reviewer documentation-specialist performance-optimizer medicines-intelligence-analyst project-analyst team-configurator tech-lead-orchestrator data-scientist postgres-expert sql-pro django-api-developer django-backend-expert django-orm-expert laravel-backend-expert laravel-eloquent-expert actix-expert android-expert angular-expert angularjs-expert ansible-expert aspnet-core-expert astro-expert auth0-expert ava-expert braintree-expert bullmq-expert bun-expert c-expert cassandra-expert celery-expert circleci-expert clojure-expert cockroachdb-expert cpp-expert csharp-expert css-expert cypress-expert dart-expert deno-expert django-expert docker-expert dynamodb-expert elasticsearch-expert electron-expert elixir-expert elk-expert erlang-expert expo-expert express-expert fastapi-expert fastify-expert fiber-expert flask-expert flutter-expert flyway-expert gin-expert github-actions-expert gitlab-ci-expert go-expert grafana-expert graphql-expert grpc-expert haskell-expert html-expert ios-expert jasmine-expert java-expert javascript-expert jenkins-expert jest-expert jquery-expert jwt-expert kafka-expert keycloak-expert knex-expert kotlin-expert kubernetes-expert langchain-expert laravel-expert liquibase-expert loki-expert lua-expert mariadb-expert mocha-expert mongodb-expert mongoose-expert mqtt-expert mssql-expert mysql-expert nats-expert neo4j-expert nestjs-expert nextjs-expert nodejs-expert numpy-expert oauth-oidc-expert ocaml-expert openai-api-expert openapi-expert opensearch-expert opentelemetry-expert owasp-top10-expert pandas-expert perl-expert phoenix-expert php-expert playwright-expert prisma-expert prometheus-expert pulumi-expert puppeteer-expert python-expert pytorch-expert rabbitmq-expert rails-expert react-expert react-native-expert redis-expert remix-expert rest-expert rollup-expert ruby-expert rust-expert scala-expert scikit-learn-expert selenium-expert sequelize-expert sidekiq-expert sns-expert solidjs-expert spring-boot-expert sql-expert sqlite-expert sqs-expert stripe-expert svelte-expert swift-expert swiftui-expert tailwind-expert tauri-expert tensorflow-expert terraform-expert testcafe-expert trpc-expert typeorm-expert typescript-expert vector-db-expert vitest-expert vue-expert webpack-expert websocket-expert rails-activerecord-expert rails-api-developer react-component-architect react-nextjs-expert vue-component-architect vue-nuxt-expert api-architect backend-developer frontend-developer tailwind-frontend-expert


I'll start by reading the required files in order.


     1ÔåÆ# Progress Log - Drug-Aware Indication Matching
     2ÔåÆ
     3ÔåÆ## Project Context
     4ÔåÆ
     5ÔåÆThis project extends the indication-based pathway charts (Phase 1-5 complete) with drug-aware matching.
     6ÔåÆ
     7ÔåÆ**Previous state**: Patients get ONE indication based on their most recent GP diagnosis match (SNOMED cluster codes). This ignores which drugs the patient is taking.
     8ÔåÆ
     9ÔåÆ**New goal**: Match each drug to an indication by cross-referencing the patient's GP diagnoses AND the drug's Search_Term mapping from DimSearchTerm.csv.
    10ÔåÆ
    11ÔåÆ## Key Data/Patterns
    12ÔåÆ
    13ÔåÆ### DimSearchTerm.csv
    14ÔåÆ- Located at `data/DimSearchTerm.csv`
    15ÔåÆ- Columns: Search_Term, CleanedDrugName (pipe-separated), PrimaryDirectorate
    16ÔåÆ- ~165 rows mapping clinical conditions to drug name fragments
    17ÔåÆ- Drug fragments are substrings that match standardized drug names from HCD data
    18ÔåÆ- Some entries have generic fragments: INHALED, CONTINUOUS, STANDARD-DOSE, PEGYLATED
    19ÔåÆ
    20ÔåÆ### Current get_patient_indication_groups() in diagnosis_lookup.py
    21ÔåÆ- Uses CLUSTER_MAPPING_SQL as CTE in Snowflake query
    22ÔåÆ- Returns ONLY the most recent match per patient (QUALIFY ROW_NUMBER() = 1)
    23ÔåÆ- Needs to return ALL matching Search_Terms per patient (remove QUALIFY)
    24ÔåÆ- Batches 500 patients per query
    25ÔåÆ
    26ÔåÆ### Modified UPID approach
    27ÔåÆ- Current: UPID = Provider Code[:3] + PersonKey (e.g., "RMV12345")
    28ÔåÆ- New: UPID = original + "|" + search_term (e.g., "RMV12345|rheumatoid arthritis")
    29ÔåÆ- The pipe delimiter "|" is safe because existing UPIDs are alphanumeric
    30ÔåÆ- generate_icicle_chart_indication() treats UPID as an opaque identifier ÔÇö modified UPIDs work transparently
    31ÔåÆ- The " - " delimiter in pathway ids is used for hierarchy levels, not within UPIDs
    32ÔåÆ
    33ÔåÆ### PseudoNHSNoLinked mapping
    34ÔåÆ- HCD data has PseudoNHSNoLinked column that matches PatientPseudonym in GP records
    35ÔåÆ- PersonKey is provider-specific local ID ÔÇö do NOT use for GP matching
    36ÔåÆ- One PseudoNHSNoLinked can map to multiple UPIDs (multi-provider patients)
    37ÔåÆ- GP match lookup: PseudoNHSNoLinked ÔåÆ list of matched Search_Terms
    38ÔåÆ
    39ÔåÆ### Drug matching logic
    40ÔåÆ- For each HCD row (UPID + Drug Name):
    41ÔåÆ  1. Get patient's GP-matched Search_Terms with code_frequency (via PseudoNHSNoLinked)
    42ÔåÆ  2. Get which Search_Terms list this drug (from DimSearchTerm.csv)
    43ÔåÆ  3. Intersection = valid indications
    44ÔåÆ  4. If 1: use it. If multiple: pick highest code_frequency (most GP coding = most likely indication). If 0: fallback to directory.
    45ÔåÆ- Modified UPID groups drugs under same indication together naturally
    46ÔåÆ- code_frequency = COUNT(*) of matching SNOMED codes per Search_Term per patient in GP records
    47ÔåÆ- GP code time range: only count codes from MIN(Intervention Date) onwards (the HCD data window)
    48ÔåÆ  - Reduces noise from old/irrelevant diagnoses, makes frequency more meaningful
    49ÔåÆ  - Pass earliest_hcd_date as parameter to get_patient_indication_groups()
    50ÔåÆ- Tiebreaker rationale: 47 RA codes vs 2 crohn's codes ÔåÆ RA is clearly the active condition
    51ÔåÆ
    52ÔåÆ### Known edge cases
    53ÔåÆ- Some DimSearchTerm drug fragments are generic (INHALED, ORAL, CONTINUOUS)
    54ÔåÆ  - These could match broadly but are constrained by GP diagnosis requirement
    55ÔåÆ- A patient visiting multiple providers has multiple UPIDs
    56ÔåÆ  - Each UPID gets its own drug-indication matching independently
    57ÔåÆ- Same Search_Term appears twice in DimSearchTerm.csv with different directorates
    58ÔåÆ  - e.g., "diabetes" ÔåÆ DIABETIC MEDICINE and OPHTHALMOLOGY
    59ÔåÆ  - For indication charts, we use Search_Term not directorate, so this is fine
    60ÔåÆ
    61ÔåÆ## Iteration Log
    62ÔåÆ

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

# Progress Log - Drug-Aware Indication Matching

## Project Context

This project extends the indication-based pathway charts (Phase 1-5 complete) with drug-aware matching.

**Previous state**: Patients get ONE indication based on their most recent GP diagnosis match (SNOMED cluster codes). This ignores which drugs the patient is taking.

**New goal**: Match each drug to an indication by cross-referencing the patient's GP diagnoses AND the drug's Search_Term mapping from DimSearchTerm.csv.

## Key Data/Patterns

### DimSearchTerm.csv
- Located at `data/DimSearchTerm.csv`
- Columns: Search_Term, CleanedDrugName (pipe-separated), PrimaryDirectorate
- ~165 rows mapping clinical conditions to drug name fragments
- Drug fragments are substrings that match standardized drug names from HCD data
- Some entries have generic fragments: INHALED, CONTINUOUS, STANDARD-DOSE, PEGYLATED

### Current get_patient_indication_groups() in diagnosis_lookup.py
- Uses CLUSTER_MAPPING_SQL as CTE in Snowflake query
- Returns ONLY the most recent match per patient (QUALIFY ROW_NUMBER() = 1)
- Needs to return ALL matching Search_Terms per patient (remove QUALIFY)
- Batches 500 patients per query

### Modified UPID approach
- Current: UPID = Provider Code[:3] + PersonKey (e.g., "RMV12345")
- New: UPID = original + "|" + search_term (e.g., "RMV12345|rheumatoid arthritis")
- The pipe delimiter "|" is safe because existing UPIDs are alphanumeric
- generate_icicle_chart_indication() treats UPID as an opaque identifier ÔÇö modified UPIDs work transparently
- The " - " delimiter in pathway ids is used for hierarchy levels, not within UPIDs

### PseudoNHSNoLinked mapping
- HCD data has PseudoNHSNoLinked column that matches PatientPseudonym in GP records
- PersonKey is provider-specific local ID ÔÇö do NOT use for GP matching
- One PseudoNHSNoLinked can map to multiple UPIDs (multi-provider patients)
- GP match lookup: PseudoNHSNoLinked ÔåÆ list of matched Search_Terms

### Drug matching logic
- For each HCD row (UPID + Drug Name):
  1. Get patient's GP-matched Search_Terms with code_frequency (via PseudoNHSNoLinked)
  2. Get which Search_Terms list this drug (from DimSearchTerm.csv)
  3. Intersection = valid indications
  4. If 1: use it. If multiple: pick highest code_frequency (most GP coding = most likely indication). If 0: fallback to directory.
- Modified UPID groups drugs under same indication together naturally
- code_frequency = COUNT(*) of matching SNOMED codes per Search_Term per patient in GP records
- GP code time range: only count codes from MIN(Intervention Date) onwards (the HCD data window)
  - Reduces noise from old/irrelevant diagnoses, makes frequency more meaningful
  - Pass earliest_hcd_date as parameter to get_patient_indication_groups()
- Tiebreaker rationale: 47 RA codes vs 2 crohn's codes ÔåÆ RA is clearly the active condition

### Known edge cases
- Some DimSearchTerm drug fragments are generic (INHALED, ORAL, CONTINUOUS)
  - These could match broadly but are constrained by GP diagnosis requirement
- A patient visiting multiple providers has multiple UPIDs
  - Each UPID gets its own drug-indication matching independently
- Same Search_Term appears twice in DimSearchTerm.csv with different directorates
  - e.g., "diabetes" ÔåÆ DIABETIC MEDICINE and OPHTHALMOLOGY
  - For indication charts, we use Search_Term not directorate, so this is fine

## Iteration Log


     1ÔåÆ# Implementation Plan - Drug-Aware Indication Matching
     2ÔåÆ
     3ÔåÆ## Project Overview
     4ÔåÆ
     5ÔåÆUpdate the indication-based pathway charts so that patient indications are matched **per drug**, not just per patient. Currently, each patient gets ONE indication (most recent GP diagnosis match). This ignores which drugs the patient is actually taking.
     6ÔåÆ
     7ÔåÆ### The Problem
     8ÔåÆ
     9ÔåÆA patient on ADALIMUMAB + OMALIZUMAB currently gets assigned a single indication (e.g., "rheumatoid arthritis" ÔÇö the most recent GP match). But:
    10ÔåÆ- ADALIMUMAB is used for rheumatoid arthritis, axial spondyloarthritis, crohn's disease, etc.
    11ÔåÆ- OMALIZUMAB is used for asthma, allergic asthma, urticaria
    12ÔåÆ
    13ÔåÆThese are different clinical pathways and should be treated as separate treatment journeys.
    14ÔåÆ
    15ÔåÆ### The Solution
    16ÔåÆ
    17ÔåÆMatch each drug to an indication by cross-referencing:
    18ÔåÆ1. **GP diagnosis** ÔÇö which Search_Terms the patient has matching SNOMED codes for
    19ÔåÆ2. **Drug mapping** ÔÇö which Search_Terms list each drug (from `DimSearchTerm.csv`)
    20ÔåÆ
    21ÔåÆOnly assign a drug to an indication if BOTH conditions are met. If a patient's drugs map to different indications, they become separate pathways (via modified UPID).
    22ÔåÆ
    23ÔåÆ### Key Design Decisions
    24ÔåÆ
    25ÔåÆ| Aspect | Decision |
    26ÔåÆ|--------|----------|
    27ÔåÆ| Drug-indication source | `data/DimSearchTerm.csv` ÔÇö Search_Term ÔåÆ CleanedDrugName mapping |
    28ÔåÆ| UPID modification | `{original_UPID}\|{search_term}` for drugs with matched indication |
    29ÔåÆ| GP diagnosis matching | Return ALL matches per patient (not just most recent) |
    30ÔåÆ| Drug matching | Substring match: HCD drug name contains DimSearchTerm fragment |
    31ÔåÆ| Multiple indication matches per drug | Use highest GP code frequency as tiebreaker (COUNT of matching SNOMED codes per Search_Term) |
    32ÔåÆ| GP code time range | Only codes from MIN(Intervention Date) onwards ÔÇö restricts to HCD data window |
    33ÔåÆ| No indication match | Fallback to directory (same as current behavior) |
    34ÔåÆ| Same patient, different indications | Separate pathways via different modified UPIDs |
    35ÔåÆ
    36ÔåÆ### Examples
    37ÔåÆ
    38ÔåÆ**Patient on ADALIMUMAB + GOLIMUMAB, GP dx: axial spondyloarthritis + asthma**
    39ÔåÆ- axial spondyloarthritis drug list includes both ADALIMUMAB and GOLIMUMAB
    40ÔåÆ- ÔåÆ Both drugs grouped under "axial spondyloarthritis", single pathway
    41ÔåÆ- Modified UPID: `RMV12345|axial spondyloarthritis`
    42ÔåÆ
    43ÔåÆ**Patient on ADALIMUMAB + OMALIZUMAB, GP dx: axial spondyloarthritis + asthma**
    44ÔåÆ- axial spondyloarthritis lists ADALIMUMAB but not OMALIZUMAB
    45ÔåÆ- asthma lists OMALIZUMAB but not ADALIMUMAB
    46ÔåÆ- ÔåÆ Two separate pathways:
    47ÔåÆ  - `RMV12345|axial spondyloarthritis` with ADALIMUMAB
    48ÔåÆ  - `RMV12345|asthma` with OMALIZUMAB
    49ÔåÆ
    50ÔåÆ**Patient on ADALIMUMAB, GP dx: rheumatoid arthritis (47 codes) + crohn's disease (2 codes)**
    51ÔåÆ- Both Search_Terms list ADALIMUMAB AND patient has GP dx for both
    52ÔåÆ- ÔåÆ Tiebreaker: highest code frequency ÔÇö rheumatoid arthritis has 47 matching SNOMED codes vs 2 for crohn's
    53ÔåÆ- ÔåÆ Single pathway under rheumatoid arthritis (more clinical activity = more likely the treatment indication)
    54ÔåÆ
    55ÔåÆ---
    56ÔåÆ
    57ÔåÆ## Phase 1: Update Snowflake Query & Drug Mapping
    58ÔåÆ
    59ÔåÆ### 1.1 Update `get_patient_indication_groups()` to return ALL matches with frequency
    60ÔåÆ- [ ] Modify the Snowflake query in `get_patient_indication_groups()` (diagnosis_lookup.py):
    61ÔåÆ  - Remove `QUALIFY ROW_NUMBER() OVER (PARTITION BY ... ORDER BY EventDateTime DESC) = 1`
    62ÔåÆ  - Return ALL matching Search_Terms per patient with code frequency:
    63ÔåÆ    ```sql
    64ÔåÆ    SELECT pc."PatientPseudonym" AS "PatientPseudonym",
    65ÔåÆ           aic.Search_Term AS "Search_Term",
    66ÔåÆ           COUNT(*) AS "code_frequency"
    67ÔåÆ    FROM PrimaryCareClinicalCoding pc
    68ÔåÆ    JOIN AllIndicationCodes aic ON pc."SNOMEDCode" = aic.SNOMEDCode
    69ÔåÆ    WHERE pc."PatientPseudonym" IN (...)
    70ÔåÆ      AND pc."EventDateTime" >= :earliest_hcd_date
    71ÔåÆ    GROUP BY pc."PatientPseudonym", aic.Search_Term
    72ÔåÆ    ```
    73ÔåÆ  - `code_frequency` = number of matching SNOMED codes per Search_Term per patient
    74ÔåÆ  - Higher frequency = more clinical activity = stronger signal for tiebreaker
    75ÔåÆ  - `earliest_hcd_date` = `MIN(Intervention Date)` from the HCD DataFrame ÔÇö restricts GP codes to the HCD data window, reducing noise from old/irrelevant diagnoses
    76ÔåÆ- [ ] Accept `earliest_hcd_date` parameter in `get_patient_indication_groups()` and pass to query
    77ÔåÆ- [ ] Keep batch processing (500 patients per query)
    78ÔåÆ- [ ] Update return type: DataFrame now has multiple rows per patient (PatientPseudonym, Search_Term, code_frequency)
    79ÔåÆ- [ ] Verify: Query returns more rows than before (patients with multiple matching diagnoses)
    80ÔåÆ
    81ÔåÆ### 1.2 Build drug-to-Search_Term lookup from DimSearchTerm.csv
    82ÔåÆ- [ ] Add function `load_drug_indication_mapping()` to `diagnosis_lookup.py`:
    83ÔåÆ  - Loads `data/DimSearchTerm.csv`
    84ÔåÆ  - Builds dict: `drug_fragment (uppercase) ÔåÆ list[Search_Term]`
    85ÔåÆ  - Also builds reverse: `search_term ÔåÆ list[drug_fragments]`
    86ÔåÆ  - CleanedDrugName is pipe-separated (e.g., "ADALIMUMAB|GOLIMUMAB|IXEKIZUMAB")
    87ÔåÆ- [ ] Add function `drug_matches_search_term(drug_name: str, search_term: str, mapping: dict) -> bool`:
    88ÔåÆ  - Checks if the drug name matches any fragment in the Search_Term's drug list
    89ÔåÆ  - Match logic: any fragment from DimSearchTerm is a substring of the drug name (case-insensitive)
    90ÔåÆ- [ ] Verify: ADALIMUMAB matches "axial spondyloarthritis", OMALIZUMAB matches "asthma"
    91ÔåÆ
    92ÔåÆ---
    93ÔåÆ
    94ÔåÆ## Phase 2: Drug-Aware Indication Matching Logic
    95ÔåÆ
    96ÔåÆ### 2.1 Create `assign_drug_indications()` function
    97ÔåÆ- [ ] Add to `diagnosis_lookup.py` or `pathway_pipeline.py`:
    98ÔåÆ  ```
    99ÔåÆ  def assign_drug_indications(
   100ÔåÆ      df: pd.DataFrame,              # HCD data with UPID, Drug Name columns
   101ÔåÆ      gp_matches_df: pd.DataFrame,   # PatientPseudonym ÔåÆ list of matched Search_Terms
   102ÔåÆ      drug_mapping: dict,             # From load_drug_indication_mapping()
   103ÔåÆ  ) -> tuple[pd.DataFrame, pd.DataFrame]:
   104ÔåÆ      Returns: (modified_df, indication_df)
   105ÔåÆ      - modified_df: HCD data with UPID replaced by {UPID}|{indication}
   106ÔåÆ      - indication_df: mapping modified_UPID ÔåÆ Search_Term
   107ÔåÆ  ```
   108ÔåÆ- [ ] Logic per UPID + Drug Name pair:
   109ÔåÆ  1. Get patient's GP-matched Search_Terms with code_frequency (from gp_matches_df via PseudoNHSNoLinked)
   110ÔåÆ  2. Get which Search_Terms include this drug (from drug_mapping)
   111ÔåÆ  3. Intersection = valid indications for this drug-patient pair
   112ÔåÆ  4. If 1 match: use it
   113ÔåÆ  5. If multiple matches: use highest code_frequency as tiebreaker (most GP coding activity = most likely treatment indication)
   114ÔåÆ  6. If 0 matches: use fallback directory
   115ÔåÆ- [ ] Modify UPID in df rows: `{original_UPID}|{matched_search_term}`
   116ÔåÆ- [ ] Build indication_df: `{modified_UPID}` ÔåÆ `Search_Term` (or fallback label)
   117ÔåÆ- [ ] Verify: Function compiles, handles edge cases (no GP match, no drug match)
   118ÔåÆ
   119ÔåÆ### 2.2 Handle tiebreaker for multiple indication matches
   120ÔåÆ- [ ] When a drug matches multiple Search_Terms AND patient has GP dx for multiple:
   121ÔåÆ  - Use `code_frequency` from the GP query (COUNT of matching SNOMED codes per Search_Term)
   122ÔåÆ  - Higher code_frequency = more clinical activity for that condition = more likely treatment indication
   123ÔåÆ  - E.g., patient with 47 RA codes and 2 crohn's codes ÔåÆ ADALIMUMAB assigned to RA
   124ÔåÆ  - code_frequency is already returned by the updated query in Task 1.1
   125ÔåÆ- [ ] Verify: Tiebreaker logic correctly picks highest-frequency diagnosis
   126ÔåÆ- [ ] Verify: Tie on frequency (rare but possible) falls back to alphabetical Search_Term for determinism
   127ÔåÆ
   128ÔåÆ---
   129ÔåÆ
   130ÔåÆ## Phase 3: Pipeline Integration
   131ÔåÆ
   132ÔåÆ### 3.1 Update `refresh_pathways.py` indication processing
   133ÔåÆ- [ ] In the `elif current_chart_type == "indication":` block:
   134ÔåÆ  1. Call `get_patient_indication_groups()` as before (but now returns ALL matches)
   135ÔåÆ  2. Load drug mapping: `drug_mapping = load_drug_indication_mapping()`
   136ÔåÆ  3. Call `assign_drug_indications(df, gp_matches_df, drug_mapping)`
   137ÔåÆ  4. Use modified_df (with indication-aware UPIDs) for pathway processing
   138ÔåÆ  5. Use indication_df for the indication mapping
   139ÔåÆ- [ ] Pass modified_df (not original df) to `process_indication_pathway_for_date_filter()`
   140ÔåÆ- [ ] Verify: Pipeline compiles, `python -m py_compile cli/refresh_pathways.py`
   141ÔåÆ
   142ÔåÆ### 3.2 Test with dry run
   143ÔåÆ- [ ] Run `python -m cli.refresh_pathways --chart-type indication --dry-run -v`
   144ÔåÆ- [ ] Verify:
   145ÔåÆ  - Modified UPIDs appear in pipeline log (e.g., `RMV12345|rheumatoid arthritis`)
   146ÔåÆ  - Patient counts are reasonable (will be higher than before since same patient can appear under multiple indications)
   147ÔåÆ  - Drug-indication matching is logged (match rate, fallback rate)
   148ÔåÆ  - Pathway hierarchy shows drug-specific grouping under correct indications
   149ÔåÆ
   150ÔåÆ---
   151ÔåÆ
   152ÔåÆ## Phase 4: Full Refresh & Validation
   153ÔåÆ
   154ÔåÆ### 4.1 Full refresh with both chart types
   155ÔåÆ- [ ] Run `python -m cli.refresh_pathways --chart-type all`
   156ÔåÆ- [ ] Verify:
   157ÔåÆ  - Both chart types generate data
   158ÔåÆ  - Directory charts unchanged (no modified UPIDs)
   159ÔåÆ  - Indication charts reflect drug-aware matching
   160ÔåÆ
   161ÔåÆ### 4.2 Validate indication chart correctness
   162ÔåÆ- [ ] Check that drugs under an indication all appear in that Search_Term's drug list
   163ÔåÆ- [ ] Verify that a patient on drugs for different indications creates separate pathway branches
   164ÔåÆ- [ ] Verify that drugs sharing an indication are grouped in the same pathway
   165ÔåÆ- [ ] Log: patient count comparison (old vs new approach)
   166ÔåÆ
   167ÔåÆ### 4.3 Validate Reflex UI
   168ÔåÆ- [ ] Run `python -m reflex compile` to verify app compiles
   169ÔåÆ- [ ] Verify chart type toggle still works
   170ÔåÆ- [ ] Verify indication chart shows correct hierarchy
   171ÔåÆ
   172ÔåÆ---
   173ÔåÆ
   174ÔåÆ## Completion Criteria
   175ÔåÆ
   176ÔåÆAll tasks marked `[x]` AND:
   177ÔåÆ- [ ] App compiles without errors (`reflex compile` succeeds)
   178ÔåÆ- [ ] Both chart types generate pathway data
   179ÔåÆ- [ ] Indication charts show drug-specific indication matching
   180ÔåÆ- [ ] Drugs under the same indication for the same patient are in one pathway
   181ÔåÆ- [ ] Drugs under different indications for the same patient create separate pathways
   182ÔåÆ- [ ] Fallback works for drugs with no indication match
   183ÔåÆ- [ ] Full refresh completes successfully
   184ÔåÆ- [ ] Existing directory charts are unaffected
   185ÔåÆ
   186ÔåÆ---
   187ÔåÆ
   188ÔåÆ## Reference
   189ÔåÆ
   190ÔåÆ### DimSearchTerm.csv Structure
   191ÔåÆ```
   192ÔåÆSearch_Term,CleanedDrugName,PrimaryDirectorate
   193ÔåÆrheumatoid arthritis,ABATACEPT|ADALIMUMAB|ANAKINRA|BARICITINIB|...,RHEUMATOLOGY
   194ÔåÆasthma,BENRALIZUMAB|DUPILUMAB|INHALED|MEPOLIZUMAB|OMALIZUMAB|RESLIZUMAB,THORACIC MEDICINE
   195ÔåÆ```
   196ÔåÆ
   197ÔåÆ### Modified UPID Format
   198ÔåÆ```
   199ÔåÆOriginal:  RMV12345
   200ÔåÆModified:  RMV12345|rheumatoid arthritis
   201ÔåÆFallback:  RMV12345|RHEUMATOLOGY (no GP dx)
   202ÔåÆ```
   203ÔåÆ
   204ÔåÆ### Current vs New Indication Flow
   205ÔåÆ```
   206ÔåÆCURRENT:
   207ÔåÆ  Patient ÔåÆ GP dx (most recent) ÔåÆ single Search_Term ÔåÆ one pathway
   208ÔåÆ
   209ÔåÆNEW:
   210ÔåÆ  Patient + Drug A ÔåÆ GP dx matching Drug A ÔåÆ Search_Term X
   211ÔåÆ  Patient + Drug B ÔåÆ GP dx matching Drug B ÔåÆ Search_Term Y
   212ÔåÆ  ÔåÆ If X == Y: one pathway under X
   213ÔåÆ  ÔåÆ If X != Y: two pathways (modified UPIDs)
   214ÔåÆ```
   215ÔåÆ
   216ÔåÆ### Key Files
   217ÔåÆ
   218ÔåÆ| File | Changes |
   219ÔåÆ|------|---------|
   220ÔåÆ| `data_processing/diagnosis_lookup.py` | Update query, add drug mapping functions |
   221ÔåÆ| `data_processing/pathway_pipeline.py` | Possibly minor changes for modified UPIDs |
   222ÔåÆ| `cli/refresh_pathways.py` | Integrate drug-aware matching into pipeline |
   223ÔåÆ| `data/DimSearchTerm.csv` | Reference data (read-only) |
   224ÔåÆ| `analysis/pathway_analyzer.py` | No changes expected (UPID changes are transparent) |
   225ÔåÆ| `pathways_app/pathways_app.py` | No changes expected |
   226ÔåÆ

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

# Implementation Plan - Drug-Aware Indication Matching

## Project Overview

Update the indication-based pathway charts so that patient indications are matched **per drug**, not just per patient. Currently, each patient gets ONE indication (most recent GP diagnosis match). This ignores which drugs the patient is actually taking.

### The Problem

A patient on ADALIMUMAB + OMALIZUMAB currently gets assigned a single indication (e.g., "rheumatoid arthritis" ÔÇö the most recent GP match). But:
- ADALIMUMAB is used for rheumatoid arthritis, axial spondyloarthritis, crohn's disease, etc.
- OMALIZUMAB is used for asthma, allergic asthma, urticaria

These are different clinical pathways and should be treated as separate treatment journeys.

### The Solution

Match each drug to an indication by cross-referencing:
1. **GP diagnosis** ÔÇö which Search_Terms the patient has matching SNOMED codes for
2. **Drug mapping** ÔÇö which Search_Terms list each drug (from `DimSearchTerm.csv`)

Only assign a drug to an indication if BOTH conditions are met. If a patient's drugs map to different indications, they become separate pathways (via modified UPID).

### Key Design Decisions

| Aspect | Decision |
|--------|----------|
| Drug-indication source | `data/DimSearchTerm.csv` ÔÇö Search_Term ÔåÆ CleanedDrugName mapping |
| UPID modification | `{original_UPID}\|{search_term}` for drugs with matched indication |
| GP diagnosis matching | Return ALL matches per patient (not just most recent) |
| Drug matching | Substring match: HCD drug name contains DimSearchTerm fragment |
| Multiple indication matches per drug | Use highest GP code frequency as tiebreaker (COUNT of matching SNOMED codes per Search_Term) |
| GP code time range | Only codes from MIN(Intervention Date) onwards ÔÇö restricts to HCD data window |
| No indication match | Fallback to directory (same as current behavior) |
| Same patient, different indications | Separate pathways via different modified UPIDs |

### Examples

**Patient on ADALIMUMAB + GOLIMUMAB, GP dx: axial spondyloarthritis + asthma**
- axial spondyloarthritis drug list includes both ADALIMUMAB and GOLIMUMAB
- ÔåÆ Both drugs grouped under "axial spondyloarthritis", single pathway
- Modified UPID: `RMV12345|axial spondyloarthritis`

**Patient on ADALIMUMAB + OMALIZUMAB, GP dx: axial spondyloarthritis + asthma**
- axial spondyloarthritis lists ADALIMUMAB but not OMALIZUMAB
- asthma lists OMALIZUMAB but not ADALIMUMAB
- ÔåÆ Two separate pathways:
  - `RMV12345|axial spondyloarthritis` with ADALIMUMAB
  - `RMV12345|asthma` with OMALIZUMAB

**Patient on ADALIMUMAB, GP dx: rheumatoid arthritis (47 codes) + crohn's disease (2 codes)**
- Both Search_Terms list ADALIMUMAB AND patient has GP dx for both
- ÔåÆ Tiebreaker: highest code frequency ÔÇö rheumatoid arthritis has 47 matching SNOMED codes vs 2 for crohn's
- ÔåÆ Single pathway under rheumatoid arthritis (more clinical activity = more likely the treatment indication)

---

## Phase 1: Update Snowflake Query & Drug Mapping

### 1.1 Update `get_patient_indication_groups()` to return ALL matches with frequency
- [ ] Modify the Snowflake query in `get_patient_indication_groups()` (diagnosis_lookup.py):
  - Remove `QUALIFY ROW_NUMBER() OVER (PARTITION BY ... ORDER BY EventDateTime DESC) = 1`
  - Return ALL matching Search_Terms per patient with code frequency:
    ```sql
    SELECT pc."PatientPseudonym" AS "PatientPseudonym",
           aic.Search_Term AS "Search_Term",
           COUNT(*) AS "code_frequency"
    FROM PrimaryCareClinicalCoding pc
    JOIN AllIndicationCodes aic ON pc."SNOMEDCode" = aic.SNOMEDCode
    WHERE pc."PatientPseudonym" IN (...)
      AND pc."EventDateTime" >= :earliest_hcd_date
    GROUP BY pc."PatientPseudonym", aic.Search_Term
    ```
  - `code_frequency` = number of matching SNOMED codes per Search_Term per patient
  - Higher frequency = more clinical activity = stronger signal for tiebreaker
  - `earliest_hcd_date` = `MIN(Intervention Date)` from the HCD DataFrame ÔÇö restricts GP codes to the HCD data window, reducing noise from old/irrelevant diagnoses
- [ ] Accept `earliest_hcd_date` parameter in `get_patient_indication_groups()` and pass to query
- [ ] Keep batch processing (500 patients per query)
- [ ] Update return type: DataFrame now has multiple rows per patient (PatientPseudonym, Search_Term, code_frequency)
- [ ] Verify: Query returns more rows than before (patients with multiple matching diagnoses)

### 1.2 Build drug-to-Search_Term lookup from DimSearchTerm.csv
- [ ] Add function `load_drug_indication_mapping()` to `diagnosis_lookup.py`:
  - Loads `data/DimSearchTerm.csv`
  - Builds dict: `drug_fragment (uppercase) ÔåÆ list[Search_Term]`
  - Also builds reverse: `search_term ÔåÆ list[drug_fragments]`
  - CleanedDrugName is pipe-separated (e.g., "ADALIMUMAB|GOLIMUMAB|IXEKIZUMAB")
- [ ] Add function `drug_matches_search_term(drug_name: str, search_term: str, mapping: dict) -> bool`:
  - Checks if the drug name matches any fragment in the Search_Term's drug list
  - Match logic: any fragment from DimSearchTerm is a substring of the drug name (case-insensitive)
- [ ] Verify: ADALIMUMAB matches "axial spondyloarthritis", OMALIZUMAB matches "asthma"

---

## Phase 2: Drug-Aware Indication Matching Logic

### 2.1 Create `assign_drug_indications()` function
- [ ] Add to `diagnosis_lookup.py` or `pathway_pipeline.py`:
  ```
  def assign_drug_indications(
      df: pd.DataFrame,              # HCD data with UPID, Drug Name columns
      gp_matches_df: pd.DataFrame,   # PatientPseudonym ÔåÆ list of matched Search_Terms
      drug_mapping: dict,             # From load_drug_indication_mapping()
  ) -> tuple[pd.DataFrame, pd.DataFrame]:
      Returns: (modified_df, indication_df)
      - modified_df: HCD data with UPID replaced by {UPID}|{indication}
      - indication_df: mapping modified_UPID ÔåÆ Search_Term
  ```
- [ ] Logic per UPID + Drug Name pair:
  1. Get patient's GP-matched Search_Terms with code_frequency (from gp_matches_df via PseudoNHSNoLinked)
  2. Get which Search_Terms include this drug (from drug_mapping)
  3. Intersection = valid indications for this drug-patient pair
  4. If 1 match: use it
  5. If multiple matches: use highest code_frequency as tiebreaker (most GP coding activity = most likely treatment indication)
  6. If 0 matches: use fallback directory
- [ ] Modify UPID in df rows: `{original_UPID}|{matched_search_term}`
- [ ] Build indication_df: `{modified_UPID}` ÔåÆ `Search_Term` (or fallback label)
- [ ] Verify: Function compiles, handles edge cases (no GP match, no drug match)

### 2.2 Handle tiebreaker for multiple indication matches
- [ ] When a drug matches multiple Search_Terms AND patient has GP dx for multiple:
  - Use `code_frequency` from the GP query (COUNT of matching SNOMED codes per Search_Term)
  - Higher code_frequency = more clinical activity for that condition = more likely treatment indication
  - E.g., patient with 47 RA codes and 2 crohn's codes ÔåÆ ADALIMUMAB assigned to RA
  - code_frequency is already returned by the updated query in Task 1.1
- [ ] Verify: Tiebreaker logic correctly picks highest-frequency diagnosis
- [ ] Verify: Tie on frequency (rare but possible) falls back to alphabetical Search_Term for determinism

---

## Phase 3: Pipeline Integration

### 3.1 Update `refresh_pathways.py` indication processing
- [ ] In the `elif current_chart_type == "indication":` block:
  1. Call `get_patient_indication_groups()` as before (but now returns ALL matches)
  2. Load drug mapping: `drug_mapping = load_drug_indication_mapping()`
  3. Call `assign_drug_indications(df, gp_matches_df, drug_mapping)`
  4. Use modified_df (with indication-aware UPIDs) for pathway processing
  5. Use indication_df for the indication mapping
- [ ] Pass modified_df (not original df) to `process_indication_pathway_for_date_filter()`
- [ ] Verify: Pipeline compiles, `python -m py_compile cli/refresh_pathways.py`

### 3.2 Test with dry run
- [ ] Run `python -m cli.refresh_pathways --chart-type indication --dry-run -v`
- [ ] Verify:
  - Modified UPIDs appear in pipeline log (e.g., `RMV12345|rheumatoid arthritis`)
  - Patient counts are reasonable (will be higher than before since same patient can appear under multiple indications)
  - Drug-indication matching is logged (match rate, fallback rate)
  - Pathway hierarchy shows drug-specific grouping under correct indications

---

## Phase 4: Full Refresh & Validation

### 4.1 Full refresh with both chart types
- [ ] Run `python -m cli.refresh_pathways --chart-type all`
- [ ] Verify:
  - Both chart types generate data
  - Directory charts unchanged (no modified UPIDs)
  - Indication charts reflect drug-aware matching

### 4.2 Validate indication chart correctness
- [ ] Check that drugs under an indication all appear in that Search_Term's drug list
- [ ] Verify that a patient on drugs for different indications creates separate pathway branches
- [ ] Verify that drugs sharing an indication are grouped in the same pathway
- [ ] Log: patient count comparison (old vs new approach)

### 4.3 Validate Reflex UI
- [ ] Run `python -m reflex compile` to verify app compiles
- [ ] Verify chart type toggle still works
- [ ] Verify indication chart shows correct hierarchy

---

## Completion Criteria

All tasks marked `[x]` AND:
- [ ] App compiles without errors (`reflex compile` succeeds)
- [ ] Both chart types generate pathway data
- [ ] Indication charts show drug-specific indication matching
- [ ] Drugs under the same indication for the same patient are in one pathway
- [ ] Drugs under different indications for the same patient create separate pathways
- [ ] Fallback works for drugs with no indication match
- [ ] Full refresh completes successfully
- [ ] Existing directory charts are unaffected

---

## Reference

### DimSearchTerm.csv Structure
```
Search_Term,CleanedDrugName,PrimaryDirectorate
rheumatoid arthritis,ABATACEPT|ADALIMUMAB|ANAKINRA|BARICITINIB|...,RHEUMATOLOGY
asthma,BENRALIZUMAB|DUPILUMAB|INHALED|MEPOLIZUMAB|OMALIZUMAB|RESLIZUMAB,THORACIC MEDICINE
```

### Modified UPID Format
```
Original:  RMV12345
Modified:  RMV12345|rheumatoid arthritis
Fallback:  RMV12345|RHEUMATOLOGY (no GP dx)
```

### Current vs New Indication Flow
```
CURRENT:
  Patient ÔåÆ GP dx (most recent) ÔåÆ single Search_Term ÔåÆ one pathway

NEW:
  Patient + Drug A ÔåÆ GP dx matching Drug A ÔåÆ Search_Term X
  Patient + Drug B ÔåÆ GP dx matching Drug B ÔåÆ Search_Term Y
  ÔåÆ If X == Y: one pathway under X
  ÔåÆ If X != Y: two pathways (modified UPIDs)
```

### Key Files

| File | Changes |
|------|---------|
| `data_processing/diagnosis_lookup.py` | Update query, add drug mapping functions |
| `data_processing/pathway_pipeline.py` | Possibly minor changes for modified UPIDs |
| `cli/refresh_pathways.py` | Integrate drug-aware matching into pipeline |
| `data/DimSearchTerm.csv` | Reference data (read-only) |
| `analysis/pathway_analyzer.py` | No changes expected (UPID changes are transparent) |
| `pathways_app/pathways_app.py` | No changes expected |


     1ÔåÆ# Guardrails
     2ÔåÆ
     3ÔåÆKnown failure patterns. Read EVERY iteration. Follow ALL of these rules.
     4ÔåÆIf you discover a new failure pattern during your work, add it to this file.
     5ÔåÆ
     6ÔåÆ---
     7ÔåÆ
     8ÔåÆ## Drug-Indication Matching Guardrails
     9ÔåÆ
    10ÔåÆ### Match drugs to indications, not just patients to indications
    11ÔåÆ- **When**: Building the indication mapping for pathway charts
    12ÔåÆ- **Rule**: Each drug must be validated against BOTH the patient's GP diagnoses AND the drug-to-indication mapping from DimSearchTerm.csv. A patient being diagnosed with rheumatoid arthritis does NOT mean all their drugs are for rheumatoid arthritis.
    13ÔåÆ- **Why**: The previous approach assigned ONE indication per patient (most recent GP dx), ignoring which drugs actually treat which conditions. This produced misleading pathways.
    14ÔåÆ
    15ÔåÆ### Use DimSearchTerm.csv for drug-to-Search_Term mapping
    16ÔåÆ- **When**: Determining which Search_Term a drug belongs to
    17ÔåÆ- **Rule**: Load `data/DimSearchTerm.csv`. The `CleanedDrugName` column has pipe-separated drug name fragments. Match HCD drug names against these fragments using substring matching (case-insensitive).
    18ÔåÆ- **Why**: This CSV is the authoritative mapping of which drugs are used for which clinical indications.
    19ÔåÆ
    20ÔåÆ### Use substring matching for drug fragments
    21ÔåÆ- **When**: Matching HCD drug names against DimSearchTerm CleanedDrugName fragments
    22ÔåÆ- **Rule**: Check if any fragment from DimSearchTerm is a SUBSTRING of the HCD drug name (case-insensitive). E.g., "PEGYLATED" should match "PEGYLATED LIPOSOMAL DOXORUBICIN".
    23ÔåÆ- **Why**: DimSearchTerm contains both full drug names (ADALIMUMAB) and partial fragments (PEGYLATED, INHALED). Exact match would miss the partial ones.
    24ÔåÆ
    25ÔåÆ### Modified UPID uses pipe delimiter
    26ÔåÆ- **When**: Creating indication-aware UPIDs
    27ÔåÆ- **Rule**: Format is `{original_UPID}|{search_term}`. Use pipe `|` as delimiter. Do NOT use ` - ` (hyphen with spaces) as that's used for pathway hierarchy levels in the `ids` column.
    28ÔåÆ- **Why**: The `ids` column uses " - " to separate hierarchy levels (e.g., "N&WICS - NNUH - rheumatoid arthritis - ADALIMUMAB"). Using the same delimiter in UPIDs would break hierarchy parsing.
    29ÔåÆ
    30ÔåÆ### Return ALL GP matches per patient, not just most recent
    31ÔåÆ- **When**: Querying Snowflake for patient GP diagnoses
    32ÔåÆ- **Rule**: Remove `QUALIFY ROW_NUMBER() OVER (PARTITION BY ... ORDER BY EventDateTime DESC) = 1`. Return ALL matching Search_Terms per patient with `GROUP BY + COUNT(*)` for code_frequency.
    33ÔåÆ- **Why**: A patient may have GP diagnoses for both rheumatoid arthritis AND asthma. We need ALL matches to cross-reference with their drugs.
    34ÔåÆ
    35ÔåÆ### Restrict GP code lookup to HCD data window
    36ÔåÆ- **When**: Building the WHERE clause for the GP record query
    37ÔåÆ- **Rule**: Add `AND pc."EventDateTime" >= :earliest_hcd_date` where `earliest_hcd_date` is `MIN(Intervention Date)` from the HCD DataFrame. Pass this as a parameter to `get_patient_indication_groups()`.
    38ÔåÆ- **Why**: Old GP codes from years before treatment started add noise. A diagnosis coded 10 years ago may no longer be relevant. Restricting to the HCD window ensures code_frequency reflects recent clinical activity for the conditions being actively treated.
    39ÔåÆ
    40ÔåÆ### Tiebreaker: highest GP code frequency when a drug matches multiple indications
    41ÔåÆ- **When**: A single drug maps to multiple Search_Terms AND the patient has GP dx for multiple
    42ÔåÆ- **Rule**: Use `code_frequency` (COUNT of matching SNOMED codes per Search_Term per patient) from the GP query. The Search_Term with the most matching codes in the patient's GP record wins. If tied, use alphabetical Search_Term for determinism.
    43ÔåÆ- **Why**: E.g., ADALIMUMAB is listed under rheumatoid arthritis, crohn's disease, psoriatic arthritis, etc. A patient with 47 RA codes and 2 crohn's codes is almost certainly on ADALIMUMAB for RA. Frequency of GP coding is a much stronger signal of clinical intent than recency ÔÇö a recent one-off asthma check doesn't mean ADALIMUMAB is for asthma.
    44ÔåÆ
    45ÔåÆ### Same patient, different indications = separate modified UPIDs
    46ÔåÆ- **When**: A patient's drugs map to different Search_Terms
    47ÔåÆ- **Rule**: Create separate modified UPIDs for each indication. E.g., `RMV12345|rheumatoid arthritis` and `RMV12345|asthma`. These are treated as separate "patients" by the pathway analyzer.
    48ÔåÆ- **Why**: This is the core design ÔÇö drugs for different indications should create separate treatment pathways, even for the same physical patient.
    49ÔåÆ
    50ÔåÆ### Fallback to directory for unmatched drugs
    51ÔåÆ- **When**: A drug doesn't match any Search_Term OR the patient has no GP dx for any of the drug's Search_Terms
    52ÔåÆ- **Rule**: Use fallback format: `{UPID}|{Directory} (no GP dx)`. The indication_df maps this to `"{Directory} (no GP dx)"`.
    53ÔåÆ- **Why**: Maintains consistent behavior with the previous approach for patients/drugs without GP diagnosis matches.
    54ÔåÆ
    55ÔåÆ### Don't modify directory chart processing
    56ÔåÆ- **When**: Making changes to the indication matching logic
    57ÔåÆ- **Rule**: Only modify the indication chart path (`elif current_chart_type == "indication":`). Directory charts use unmodified UPIDs and directory-based grouping.
    58ÔåÆ- **Why**: Directory charts work correctly and should not be affected by indication matching changes.
    59ÔåÆ
    60ÔåÆ---
    61ÔåÆ
    62ÔåÆ## Snowflake Query Guardrails
    63ÔåÆ
    64ÔåÆ### Use PseudoNHSNoLinked for GP record matching
    65ÔåÆ- **When**: Querying GP records (PrimaryCareClinicalCoding) for patient diagnoses
    66ÔåÆ- **Rule**: Use `PseudoNHSNoLinked` column from HCD data, NOT `PersonKey` (LocalPatientID)
    67ÔåÆ- **Why**: PersonKey is provider-specific local ID. Only PseudoNHSNoLinked matches PatientPseudonym in GP records.
    68ÔåÆ
    69ÔåÆ### Embed cluster query as CTE in Snowflake
    70ÔåÆ- **When**: Looking up patient indications during data refresh
    71ÔåÆ- **Rule**: Use the `CLUSTER_MAPPING_SQL` content as a WITH clause in the patient lookup query
    72ÔåÆ- **Why**: This ensures we always use the complete cluster mapping and don't need local storage
    73ÔåÆ
    74ÔåÆ### Quote mixed-case column aliases in Snowflake SQL
    75ÔåÆ- **When**: Writing SELECT queries that return results to Python code
    76ÔåÆ- **Rule**: Use `AS "ColumnName"` (quoted) for any column alias you'll access by name in Python
    77ÔåÆ- **Why**: Snowflake uppercases unquoted identifiers. `SELECT foo AS Search_Term` returns `SEARCH_TERM`, so `row.get('Search_Term')` returns None. Fix: `SELECT foo AS "Search_Term"`
    78ÔåÆ
    79ÔåÆ### Build indication_df from all unique UPIDs, not PseudoNHSNoLinked
    80ÔåÆ- **When**: Creating the indication mapping DataFrame for pathway processing
    81ÔåÆ- **Rule**: Use `df.drop_duplicates(subset=['UPID'])` not `drop_duplicates(subset=['PseudoNHSNoLinked'])`
    82ÔåÆ- **Why**: A patient visiting multiple providers has multiple UPIDs. Using unique PseudoNHSNoLinked only maps one UPID per patient, leaving others as NaN.
    83ÔåÆ
    84ÔåÆ---
    85ÔåÆ
    86ÔåÆ## Data Processing Guardrails
    87ÔåÆ
    88ÔåÆ### Copy DataFrames in functions that modify columns
    89ÔåÆ- **When**: Writing functions like `prepare_data()` that modify DataFrame columns
    90ÔåÆ- **Rule**: Always `df = df.copy()` at the start of any function that modifies column values on the input DataFrame
    91ÔåÆ- **Why**: `prepare_data()` mapped Provider Code ÔåÆ Name in-place. When called multiple times on the same DataFrame, only the first call worked. The fix: `df.copy()` prevents destructive mutation.
    92ÔåÆ
    93ÔåÆ### Include chart_type in UNIQUE constraints for pathway_nodes
    94ÔåÆ- **When**: Creating or modifying the pathway_nodes table schema
    95ÔåÆ- **Rule**: The UNIQUE constraint MUST include `chart_type`: `UNIQUE(date_filter_id, chart_type, ids)`
    96ÔåÆ- **Why**: Without `chart_type`, `INSERT OR REPLACE` silently overwrites directory chart nodes when indication chart nodes are inserted.
    97ÔåÆ
    98ÔåÆ### Handle NaN in Directory when building fallback labels
    99ÔåÆ- **When**: Creating fallback indication labels for patients without GP diagnosis match
   100ÔåÆ- **Rule**: Check `pd.notna(directory)` before concatenating to string. Use `"UNKNOWN (no GP dx)"` for NaN cases.
   101ÔåÆ- **Why**: NaN handling prevents TypeError and ensures meaningful fallback labels.
   102ÔåÆ
   103ÔåÆ### Use parameterized queries for SQLite
   104ÔåÆ- **When**: Building WHERE clauses with user-selected filters
   105ÔåÆ- **Rule**: Use `?` placeholders and pass params tuple ÔÇö never string interpolation
   106ÔåÆ- **Why**: Prevents SQL injection and handles special characters in drug/directory names
   107ÔåÆ
   108ÔåÆ### Use existing pathway_analyzer functions
   109ÔåÆ- **When**: Processing pathway data for the icicle chart
   110ÔåÆ- **Rule**: Reuse functions from `analysis/pathway_analyzer.py` ÔÇö don't reinvent
   111ÔåÆ- **Why**: The existing code handles edge cases (empty groups, statistics calculation, color mapping)
   112ÔåÆ
   113ÔåÆ---
   114ÔåÆ
   115ÔåÆ## Reflex Guardrails
   116ÔåÆ
   117ÔåÆ### Use .to() methods for Var operations in rx.foreach
   118ÔåÆ- **When**: Working with items inside `rx.foreach` render functions
   119ÔåÆ- **Rule**: Use `item.to(int)` for numeric comparisons, `item.to_string()` for text operations
   120ÔåÆ- **Why**: Items from rx.foreach are Var objects, not plain Python values.
   121ÔåÆ
   122ÔåÆ### Use rx.cond for conditional rendering, not Python if
   123ÔåÆ- **When**: Conditionally showing/hiding components or changing styles based on state
   124ÔåÆ- **Rule**: Use `rx.cond(condition, true_component, false_component)` ÔÇö not Python `if`
   125ÔåÆ- **Why**: Python `if` evaluates at definition time; `rx.cond` evaluates reactively at render time
   126ÔåÆ
   127ÔåÆ---
   128ÔåÆ
   129ÔåÆ## Process Guardrails
   130ÔåÆ
   131ÔåÆ### One task per iteration
   132ÔåÆ- **When**: Temptation to do additional tasks after completing the current one
   133ÔåÆ- **Rule**: Complete ONE task, validate it, commit it, update progress, then stop
   134ÔåÆ- **Why**: Multiple tasks increase error risk and make failures harder to diagnose
   135ÔåÆ
   136ÔåÆ### Never mark complete without validation
   137ÔåÆ- **When**: Task feels "done" but hasn't been tested
   138ÔåÆ- **Rule**: All validation tiers must pass before marking `[x]`
   139ÔåÆ- **Why**: "Feels done" is not "is done"
   140ÔåÆ
   141ÔåÆ### Write explicit handoff notes
   142ÔåÆ- **When**: Every iteration, before stopping
   143ÔåÆ- **Rule**: The "Next iteration should" section must contain specific, actionable guidance
   144ÔåÆ- **Why**: The next iteration has zero memory. If you don't write it down, it's lost.
   145ÔåÆ
   146ÔåÆ### Check existing code for patterns
   147ÔåÆ- **When**: Unsure how to implement something
   148ÔåÆ- **Rule**: Look at `pathways_app/pathways_app.py`, `analysis/pathway_analyzer.py`, `cli/refresh_pathways.py`
   149ÔåÆ- **Why**: The existing codebase has solved many quirks already
   150ÔåÆ
   151ÔåÆ<!--
   152ÔåÆADD NEW GUARDRAILS BELOW as failures are observed during the loop.
   153ÔåÆ
   154ÔåÆFormat:
   155ÔåÆ### [Short descriptive name]
   156ÔåÆ- **When**: What situation triggers this guardrail?
   157ÔåÆ- **Rule**: What must you do (or not do)?
   158ÔåÆ- **Why**: What failure prompted adding this guardrail?
   159ÔåÆ-->
   160ÔåÆ

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

# Guardrails

Known failure patterns. Read EVERY iteration. Follow ALL of these rules.
If you discover a new failure pattern during your work, add it to this file.

---

## Drug-Indication Matching Guardrails

### Match drugs to indications, not just patients to indications
- **When**: Building the indication mapping for pathway charts
- **Rule**: Each drug must be validated against BOTH the patient's GP diagnoses AND the drug-to-indication mapping from DimSearchTerm.csv. A patient being diagnosed with rheumatoid arthritis does NOT mean all their drugs are for rheumatoid arthritis.
- **Why**: The previous approach assigned ONE indication per patient (most recent GP dx), ignoring which drugs actually treat which conditions. This produced misleading pathways.

### Use DimSearchTerm.csv for drug-to-Search_Term mapping
- **When**: Determining which Search_Term a drug belongs to
- **Rule**: Load `data/DimSearchTerm.csv`. The `CleanedDrugName` column has pipe-separated drug name fragments. Match HCD drug names against these fragments using substring matching (case-insensitive).
- **Why**: This CSV is the authoritative mapping of which drugs are used for which clinical indications.

### Use substring matching for drug fragments
- **When**: Matching HCD drug names against DimSearchTerm CleanedDrugName fragments
- **Rule**: Check if any fragment from DimSearchTerm is a SUBSTRING of the HCD drug name (case-insensitive). E.g., "PEGYLATED" should match "PEGYLATED LIPOSOMAL DOXORUBICIN".
- **Why**: DimSearchTerm contains both full drug names (ADALIMUMAB) and partial fragments (PEGYLATED, INHALED). Exact match would miss the partial ones.

### Modified UPID uses pipe delimiter
- **When**: Creating indication-aware UPIDs
- **Rule**: Format is `{original_UPID}|{search_term}`. Use pipe `|` as delimiter. Do NOT use ` - ` (hyphen with spaces) as that's used for pathway hierarchy levels in the `ids` column.
- **Why**: The `ids` column uses " - " to separate hierarchy levels (e.g., "N&WICS - NNUH - rheumatoid arthritis - ADALIMUMAB"). Using the same delimiter in UPIDs would break hierarchy parsing.

### Return ALL GP matches per patient, not just most recent
- **When**: Querying Snowflake for patient GP diagnoses
- **Rule**: Remove `QUALIFY ROW_NUMBER() OVER (PARTITION BY ... ORDER BY EventDateTime DESC) = 1`. Return ALL matching Search_Terms per patient with `GROUP BY + COUNT(*)` for code_frequency.
- **Why**: A patient may have GP diagnoses for both rheumatoid arthritis AND asthma. We need ALL matches to cross-reference with their drugs.

### Restrict GP code lookup to HCD data window
- **When**: Building the WHERE clause for the GP record query
- **Rule**: Add `AND pc."EventDateTime" >= :earliest_hcd_date` where `earliest_hcd_date` is `MIN(Intervention Date)` from the HCD DataFrame. Pass this as a parameter to `get_patient_indication_groups()`.
- **Why**: Old GP codes from years before treatment started add noise. A diagnosis coded 10 years ago may no longer be relevant. Restricting to the HCD window ensures code_frequency reflects recent clinical activity for the conditions being actively treated.

### Tiebreaker: highest GP code frequency when a drug matches multiple indications
- **When**: A single drug maps to multiple Search_Terms AND the patient has GP dx for multiple
- **Rule**: Use `code_frequency` (COUNT of matching SNOMED codes per Search_Term per patient) from the GP query. The Search_Term with the most matching codes in the patient's GP record wins. If tied, use alphabetical Search_Term for determinism.
- **Why**: E.g., ADALIMUMAB is listed under rheumatoid arthritis, crohn's disease, psoriatic arthritis, etc. A patient with 47 RA codes and 2 crohn's codes is almost certainly on ADALIMUMAB for RA. Frequency of GP coding is a much stronger signal of clinical intent than recency ÔÇö a recent one-off asthma check doesn't mean ADALIMUMAB is for asthma.

### Same patient, different indications = separate modified UPIDs
- **When**: A patient's drugs map to different Search_Terms
- **Rule**: Create separate modified UPIDs for each indication. E.g., `RMV12345|rheumatoid arthritis` and `RMV12345|asthma`. These are treated as separate "patients" by the pathway analyzer.
- **Why**: This is the core design ÔÇö drugs for different indications should create separate treatment pathways, even for the same physical patient.

### Fallback to directory for unmatched drugs
- **When**: A drug doesn't match any Search_Term OR the patient has no GP dx for any of the drug's Search_Terms
- **Rule**: Use fallback format: `{UPID}|{Directory} (no GP dx)`. The indication_df maps this to `"{Directory} (no GP dx)"`.
- **Why**: Maintains consistent behavior with the previous approach for patients/drugs without GP diagnosis matches.

### Don't modify directory chart processing
- **When**: Making changes to the indication matching logic
- **Rule**: Only modify the indication chart path (`elif current_chart_type == "indication":`). Directory charts use unmodified UPIDs and directory-based grouping.
- **Why**: Directory charts work correctly and should not be affected by indication matching changes.

---

## Snowflake Query Guardrails

### Use PseudoNHSNoLinked for GP record matching
- **When**: Querying GP records (PrimaryCareClinicalCoding) for patient diagnoses
- **Rule**: Use `PseudoNHSNoLinked` column from HCD data, NOT `PersonKey` (LocalPatientID)
- **Why**: PersonKey is provider-specific local ID. Only PseudoNHSNoLinked matches PatientPseudonym in GP records.

### Embed cluster query as CTE in Snowflake
- **When**: Looking up patient indications during data refresh
- **Rule**: Use the `CLUSTER_MAPPING_SQL` content as a WITH clause in the patient lookup query
- **Why**: This ensures we always use the complete cluster mapping and don't need local storage

### Quote mixed-case column aliases in Snowflake SQL
- **When**: Writing SELECT queries that return results to Python code
- **Rule**: Use `AS "ColumnName"` (quoted) for any column alias you'll access by name in Python
- **Why**: Snowflake uppercases unquoted identifiers. `SELECT foo AS Search_Term` returns `SEARCH_TERM`, so `row.get('Search_Term')` returns None. Fix: `SELECT foo AS "Search_Term"`

### Build indication_df from all unique UPIDs, not PseudoNHSNoLinked
- **When**: Creating the indication mapping DataFrame for pathway processing
- **Rule**: Use `df.drop_duplicates(subset=['UPID'])` not `drop_duplicates(subset=['PseudoNHSNoLinked'])`
- **Why**: A patient visiting multiple providers has multiple UPIDs. Using unique PseudoNHSNoLinked only maps one UPID per patient, leaving others as NaN.

---

## Data Processing Guardrails

### Copy DataFrames in functions that modify columns
- **When**: Writing functions like `prepare_data()` that modify DataFrame columns
- **Rule**: Always `df = df.copy()` at the start of any function that modifies column values on the input DataFrame
- **Why**: `prepare_data()` mapped Provider Code ÔåÆ Name in-place. When called multiple times on the same DataFrame, only the first call worked. The fix: `df.copy()` prevents destructive mutation.

### Include chart_type in UNIQUE constraints for pathway_nodes
- **When**: Creating or modifying the pathway_nodes table schema
- **Rule**: The UNIQUE constraint MUST include `chart_type`: `UNIQUE(date_filter_id, chart_type, ids)`
- **Why**: Without `chart_type`, `INSERT OR REPLACE` silently overwrites directory chart nodes when indication chart nodes are inserted.

### Handle NaN in Directory when building fallback labels
- **When**: Creating fallback indication labels for patients without GP diagnosis match
- **Rule**: Check `pd.notna(directory)` before concatenating to string. Use `"UNKNOWN (no GP dx)"` for NaN cases.
- **Why**: NaN handling prevents TypeError and ensures meaningful fallback labels.

### Use parameterized queries for SQLite
- **When**: Building WHERE clauses with user-selected filters
- **Rule**: Use `?` placeholders and pass params tuple ÔÇö never string interpolation
- **Why**: Prevents SQL injection and handles special characters in drug/directory names

### Use existing pathway_analyzer functions
- **When**: Processing pathway data for the icicle chart
- **Rule**: Reuse functions from `analysis/pathway_analyzer.py` ÔÇö don't reinvent
- **Why**: The existing code handles edge cases (empty groups, statistics calculation, color mapping)

---

## Reflex Guardrails

### Use .to() methods for Var operations in rx.foreach
- **When**: Working with items inside `rx.foreach` render functions
- **Rule**: Use `item.to(int)` for numeric comparisons, `item.to_string()` for text operations
- **Why**: Items from rx.foreach are Var objects, not plain Python values.

### Use rx.cond for conditional rendering, not Python if
- **When**: Conditionally showing/hiding components or changing styles based on state
- **Rule**: Use `rx.cond(condition, true_component, false_component)` ÔÇö not Python `if`
- **Why**: Python `if` evaluates at definition time; `rx.cond` evaluates reactively at render time

---

## Process Guardrails

### One task per iteration
- **When**: Temptation to do additional tasks after completing the current one
- **Rule**: Complete ONE task, validate it, commit it, update progress, then stop
- **Why**: Multiple tasks increase error risk and make failures harder to diagnose

### Never mark complete without validation
- **When**: Task feels "done" but hasn't been tested
- **Rule**: All validation tiers must pass before marking `[x]`
- **Why**: "Feels done" is not "is done"

### Write explicit handoff notes
- **When**: Every iteration, before stopping
- **Rule**: The "Next iteration should" section must contain specific, actionable guidance
- **Why**: The next iteration has zero memory. If you don't write it down, it's lost.

### Check existing code for patterns
- **When**: Unsure how to implement something
- **Rule**: Look at `pathways_app/pathways_app.py`, `analysis/pathway_analyzer.py`, `cli/refresh_pathways.py`
- **Why**: The existing codebase has solved many quirks already

<!--
ADD NEW GUARDRAILS BELOW as failures are observed during the loop.

Format:
### [Short descriptive name]
- **When**: What situation triggers this guardrail?
- **Rule**: What must you do (or not do)?
- **Why**: What failure prompted adding this guardrail?
-->


Reading progress.txt, IMPLEMENTATION_PLAN.md, and guardrails.md. The iteration log in progress.txt is empty ÔÇö this is the **first iteration**. All tasks in IMPLEMENTATION_PLAN.md are `[ ]` (not started).

Let me check recent commits and read the key source files I'll be modifying.


Bash

cd "C:\Users\charlwoodand\Ralph local\Tasks\UI Redesign" && git log --oneline -5

Check recent git commits


1c4d2c0 docs: mark project complete - all tasks done, viewport testing blocked by env (Iteration 9)
fed9094 docs: update CLAUDE.md with indication chart architecture and CLI docs (Task 5.2)
4884e0a fix: recreate pathway_nodes with correct UNIQUE constraint and validate end-to-end (Task 5.1)
6331d44 fix: prevent DataFrame mutation in prepare_data() causing indication charts to fail
6f88a59 feat: add chart type toggle for Directory/Indication views (Task 4.1, 4.2, 4.3)


     1ÔåÆSearch_Term,CleanedDrugName,PrimaryDirectorate
     2ÔåÆacute coronary syndrome,ABCIXIMAB|CLOPIDOGREL|PRASUGREL|RIVAROXABAN|TICAGRELOR,CARDIOLOGY
     3ÔåÆacute lymphoblastic leukaemia,BLINATUMOMAB|DASATINIB|INOTUZUMAB|PEGASPARGASE|PONATINIB|TISAGENLECLEUCEL,CLINICAL HAEMATOLOGY
     4ÔåÆacute myeloid leukaemia,AZACITIDINE|DECITABINE|GEMTUZUMAB|GILTERITINIB|GLASDEGIB|LIPOSOMAL|MIDOSTAURIN|ORAL|VENETOCLAX,CLINICAL HAEMATOLOGY
     5ÔåÆacute promyelocytic leukaemia,ARSENIC|GEMTUZUMAB,CLINICAL HAEMATOLOGY
     6ÔåÆallergic asthma,OMALIZUMAB,THORACIC MEDICINE
     7ÔåÆallergic rhinitis,SQ,ENT
     8ÔåÆalzheimer's disease,DONEPEZIL,NEUROLOGY
     9ÔåÆamyloidosis,VUTRISIRAN,CLINICAL HAEMATOLOGY
    10ÔåÆanaemia,ERYTHROPOIESIS-STIMULATING|ERYTHROPOIETIN,CLINICAL HAEMATOLOGY
    11ÔåÆanaplastic large cell lymphoma,BRENTUXIMAB,CLINICAL HAEMATOLOGY
    12ÔåÆankylosing spondylitis,ADALIMUMAB|GOLIMUMAB|SECUKINUMAB|UPADACITINIB,RHEUMATOLOGY
    13ÔåÆapixaban,ANDEXANET,CARDIOLOGY
    14ÔåÆaplastic anaemia,ELTROMBOPAG,CLINICAL HAEMATOLOGY
    15ÔåÆarthritis,ETANERCEPT,RHEUMATOLOGY
    16ÔåÆasthma,BENRALIZUMAB|DUPILUMAB|INHALED|MEPOLIZUMAB|OMALIZUMAB|RESLIZUMAB,THORACIC MEDICINE
    17ÔåÆatopic dermatitis,ABROCITINIB|ALCLOMETASONE|BARICITINIB|CRISABOROLE|DUPILUMAB|PIMECROLIMUS,DERMATOLOGY
    18ÔåÆatrial fibrillation,APIXABAN|DABIGATRAN|DRONEDARONE|EDOXABAN|RIVAROXABAN|VERNAKALANT,CARDIOLOGY
    19ÔåÆattention deficit hyperactivity disorder,ATOMOXETINE,MENTAL HEALTH
    20ÔåÆattention-deficit hyperactivity disorder,METHYLPHENIDATE,MENTAL HEALTH
    21ÔåÆaxial spondyloarthritis,ADALIMUMAB|GOLIMUMAB|IXEKIZUMAB|SECUKINUMAB|UPADACITINIB,RHEUMATOLOGY
    22ÔåÆbasal cell carcinoma,VISMODEGIB,DERMATOLOGY
    23ÔåÆbipolar disorder,LOXAPINE|OLANZAPINE,MENTAL HEALTH
    24ÔåÆbladder,MIRABEGRON,MEDICAL ONCOLOGY
    25ÔåÆbrca,OLAPARIB,MEDICAL ONCOLOGY
    26ÔåÆbreast cancer,ABEMACICLIB|ALPELISIB|ANASTROZOLE|ATEZOLIZUMAB|BEVACIZUMAB|CAPECITABINE|DENOSUMAB|DOCETAXEL|ERIBULIN|EVEROLIMUS|FULVESTRANT|GEMCITABINE|INTRABEAM|LAPATINIB|NERATINIB|OLAPARIB|PACLITAXEL|PALBOCICLI|PALBOCICLIB|PEMBROLIZUMAB|PERTUZUMAB|RIBOCICLIB|SACITUZUMAB|TRASTUZUMAB|TUCATINIB|VINORELBINE,MEDICAL ONCOLOGY
    27ÔåÆcardiomyopathy,TAFAMIDIS,CARDIOLOGY
    28ÔåÆcardiovascular disease,ATORVASTATIN,CARDIOLOGY
    29ÔåÆcervical cancer,TOPOTECAN,MEDICAL ONCOLOGY
    30ÔåÆcholangiocarcinoma,PEMIGATINIB,MEDICAL ONCOLOGY
    31ÔåÆchoroidal neovascularisation,AFLIBERCEPT|RANIBIZUMAB,OPHTHALMOLOGY
    32ÔåÆchronic kidney disease,DAPAGLIFLOZIN|IMLIFIDASE|ROXADUSTAT,NEPHROLOGY
    33ÔåÆchronic liver disease,AVATROMBOPAG|LUSUTROMBOPAG,GASTROENTEROLOGY
    34ÔåÆchronic lymphocytic leukaemia,ACALABRUTINIB|BENDAMUSTINE|DUVELISIB|IBRUTINIB|IDELALISIB|OBINUTUZUMAB|OFATUMUMAB|RITUXIMAB|VENETOCLAX,CLINICAL HAEMATOLOGY
    35ÔåÆchronic myeloid leukaemia,ASCIMINIB|BOSUTINIB|STANDARD-DOSE|DASATINIB|DASITINIB|NILOTINIB|PONATINIB,CLINICAL HAEMATOLOGY
    36ÔåÆchronic obstructive pulmonary disease,ROFLUMILAST,THORACIC MEDICINE
    37ÔåÆcolon cancer,CAPECITABINE,MEDICAL ONCOLOGY
    38ÔåÆcolorectal cancer,BEVACIZUMAB|CAPECITABINE|IRINOTECAN,MEDICAL ONCOLOGY
    39ÔåÆconstipation,LUBIPROSTONE|METHYLNALTREXONE|NALDEMEDINE|NALOXEGOL|PRUCALOPRIDE,GASTROENTEROLOGY
    40ÔåÆcovid-19,NIRMATRELVIR,INFECTIOUS DISEASES
    41ÔåÆcrohn's disease,INFLIXIMAB|VEDOLIZUMAB,GASTROENTEROLOGY
    42ÔåÆcutaneous t-cell lymphoma,BRENTUXIMAB|CHLORMETHINE,CLINICAL HAEMATOLOGY
    43ÔåÆcystic fibrosis,COLISTIMETHATE|LUMACAFTOR|MANNITOL,THORACIC MEDICINE
    44ÔåÆcytomegalovirus,LETERMOVIR|MARIBAVIR,INFECTIOUS DISEASES
    45ÔåÆdeep vein thrombosis,APIXABAN|DABIGATRAN|EDOXABAN|RIVAROXABAN,VASCULAR SURGERY
    46ÔåÆdepression,ESKETAMINE,MENTAL HEALTH
    47ÔåÆdiabetes,ERTUGLIFLOZIN|INHALED|AFLIBERCEPT|BROLUCIZUMAB|DEXAMETHASONE|FARICIMAB|FLUOCINOLONE|RANIBIZUMAB,DIABETIC MEDICINE
    48ÔåÆdiabetes,ERTUGLIFLOZIN|INHALED|AFLIBERCEPT|BROLUCIZUMAB|DEXAMETHASONE|FARICIMAB|FLUOCINOLONE|RANIBIZUMAB,OPHTHALMOLOGY
    49ÔåÆdiabetic retinopathy,RANIBUZIMAB,OPHTHALMOLOGY
    50ÔåÆdiffuse large b-cell lymphoma,AXICABTAGENE|POLATUZUMAB|TISAGENLECLEUCEL,CLINICAL HAEMATOLOGY
    51ÔåÆdravet syndrome,CANNABIDIOL|FENFLURAMINE,NEUROLOGY
    52ÔåÆdrug misuse,BUPRENORPHINE|NALTREXONE,MENTAL HEALTH
    53ÔåÆdry eye,CICLOSPORIN,OPHTHALMOLOGY
    54ÔåÆdyspepsia,LANSOPRAZOLE,GASTROENTEROLOGY
    55ÔåÆendometrial cancer,DOSTARLIMAB,MEDICAL ONCOLOGY
    56ÔåÆepilepsy,CENOBAMATE|GABAPENTIN|RETIGABINE,NEUROLOGY
    57ÔåÆfallopian tube,BEVACIZUMAB|NIRAPARIB|OLAPARIB|RUCAPARIB,MEDICAL ONCOLOGY
    58ÔåÆfollicular lymphoma,DUVELISIB|IDELALISIB|LENALIDOMIDE|OBINUTUZUMAB|RITUXIMAB|TISAGENLECLEUCEL,CLINICAL HAEMATOLOGY
    59ÔåÆgastric cancer,CAPECITABINE|RAMUCIRUMAB|TRASTUZUMAB|TRIFLURIDINE,MEDICAL ONCOLOGY
    60ÔåÆgastro-oesophageal junction,NIVOLUMAB|PEMBROLIZUMAB,MEDICAL ONCOLOGY
    61ÔåÆgiant cell arteritis,TOCILIZUMAB,RHEUMATOLOGY
    62ÔåÆglioma,CARMUSTINE,MEDICAL ONCOLOGY
    63ÔåÆgout,CANAKINUMAB|FEBUXOSTAT|LESINURAD,RHEUMATOLOGY
    64ÔåÆgraft versus host disease,RUXOLITINIB,CLINICAL HAEMATOLOGY
    65ÔåÆgranulomatosis with polyangiitis,AVACOPAN|MEPOLIZUMAB,RHEUMATOLOGY
    66ÔåÆgrowth hormone deficiency,SOMATROPIN,ENDOCRINOLOGY
    67ÔåÆhand eczema,ALITRETINOIN,DERMATOLOGY
    68ÔåÆheart failure,DAPAGLIFLOZIN|EMPAGLIFLOZIN|IVABRADINE|SACUBITRIL|VERICIGUAT,CARDIOLOGY
    69ÔåÆhepatitis b,ADEFOVIR,GASTROENTEROLOGY
    70ÔåÆhepatitis c,BOCEPREVIR|DACLATASVIR|ELBASVIR|GLECAPREVIR|INTERFERON|LEDIPASVIR|OMBITASVIR|PEGINTERFERON|PEGYLATED|SIMEPREVIR|SOFOSBUVIR|TELAPREVIR,GASTROENTEROLOGY
    71ÔåÆhepatocellular carcinoma,ATEZOLIZUMAB|CABOZANTINIB|LENVATINIB|RAMUCIRUMAB|REGORAFENIB|SELECTIVE|SORAFENIB,MEDICAL ONCOLOGY
    72ÔåÆhiv,CABOTEGRAVIR,INFECTIOUS DISEASES
    73ÔåÆhodgkin lymphoma,BRENTUXIMAB|NIVOLUMAB|PEMBROLIZUMAB,CLINICAL HAEMATOLOGY
    74ÔåÆhormone receptor,ABEMACICLIB,MEDICAL ONCOLOGY
    75ÔåÆhypercholesterolaemia,EZETIMIBE,CARDIOLOGY
    76ÔåÆhyperparathyroidism,CINACALCET|ETELCALCETIDE,ENDOCRINOLOGY
    77ÔåÆimmune thrombocytopenia,AVATROMBOPAG|FOSTAMATINIB,CLINICAL HAEMATOLOGY
    78ÔåÆinfluenza,AMANTADINE|ZANAMIVIR|BALOXAVIR,INFECTIOUS DISEASES
    79ÔåÆinsomnia,ZALEPLON,NEUROLOGY
    80ÔåÆirritable bowel syndrome,ELUXADOLINE,GASTROENTEROLOGY
    81ÔåÆischaemic stroke,ALTEPLASE,STROKE MEDICINE
    82ÔåÆjuvenile idiopathic arthritis,ABATECEPT|CANAKINUMAB|TOCILIZUMAB|TOFACITINIB,RHEUMATOLOGY
    83ÔåÆkidney transplant,BASILIXIMAB,NEPHROLOGY
    84ÔåÆleukaemia,FLUDARABINE|IMATINIB,CLINICAL HAEMATOLOGY
    85ÔåÆlung cancer,ATEZOLIZUMAB|DURVALUMAB|GEFITINIB|ORAL|NINTEDANIB,MEDICAL ONCOLOGY
    86ÔåÆlymphoma,BENDAMUSTINE|CRIZOTINIB|PIXANTRONE|RITUXIMAB,CLINICAL HAEMATOLOGY
    87ÔåÆmacular degeneration,AFLIBERCEPT|BROLUCIZUMAB|FARICIMAB|RANIBIZUMAB,OPHTHALMOLOGY
    88ÔåÆmacular oedema,AFLIBERCEPT|RANIBIZUMAB,OPHTHALMOLOGY
    89ÔåÆmajor depressive episodes,AGOMELATINE|VORTIOXETINE,MENTAL HEALTH
    90ÔåÆmalignant melanoma,VEMURAFENIB,MEDICAL ONCOLOGY
    91ÔåÆmalignant pleural mesothelioma,NIVOLUMAB|PEMETREXED,MEDICAL ONCOLOGY
    92ÔåÆmanic episode,ARIPIPRAZOLE,MENTAL HEALTH
    93ÔåÆmantle cell lymphoma,AUTOLOGOUS|BORTEZOMIB|IBRUTINIB|LENALIDOMIDE|TEMSIROLIMUS,CLINICAL HAEMATOLOGY
    94ÔåÆmelanoma,COBIMETINIB|DABRAFENIB|ENCORAFENIB|IPILIMUMAB|NIVOLUMAB|PEMBROLIZUMAB|TALIMOGENE|TRAMETINIB,MEDICAL ONCOLOGY
    95ÔåÆmerkel cell carcinoma,AVELUMAB,MEDICAL ONCOLOGY
    96ÔåÆmigraine,BOTULINUM|EPTINEZUMAB|ERENUMAB|FREMANEZUMAB|GALCANEZUMAB,NEUROLOGY
    97ÔåÆmotor neurone disease,RILUZOLE,NEUROLOGY
    98ÔåÆmultiple myeloma,BORTEZOMIB|THALIDOMIDE|CARFILZOMIB|DARATUMUMAB|DENOSUMAB|ELOTUZUMAB|ISATUXIMAB|IXAZOMIB|LENALIDOMIDE|PANOBINOSTAT|POMALIDOMIDE|SELINEXOR|TECLISTAMAB,CLINICAL HAEMATOLOGY
    99ÔåÆmultiple sclerosis,ALEMTUZUMAB|BETA|CLADRIBINE|DACLIZUMAB|DIMETHYL|DIROXIMEL|FINGOLIMOD|INTERFERON|NATALIZUMAB|OCRELIZUMAB|OZANIMOD|PEGINTERFERON|PONESIMOD|SIPONIMOD|TERIFLUNOMIDE,NEUROLOGY
   100ÔåÆmyelodysplastic,LENALIDOMIDE|LUSPATERCEPT,CLINICAL HAEMATOLOGY
   101ÔåÆmyelofibrosis,FEDRATINIB|RUXOLITINIB,CLINICAL HAEMATOLOGY
   102ÔåÆmyocardial infarction,ALTEPLASE|BIVALIRUDIN|TICAGRELOR,CARDIOLOGY
   103ÔåÆmyotonia,MEXILETINE,NEUROLOGY
   104ÔåÆnarcolepsy,SOLRIAMFETOL,NEUROLOGY
   105ÔåÆneuroendocrine tumour,EVEROLIMUS|LUTETIUM,MEDICAL ONCOLOGY
   106ÔåÆnon-small cell lung cancer,ATEZOLIZMAB|DOCETAXEL|ERLOTINIB|PEMETREXED,MEDICAL ONCOLOGY
   107ÔåÆnon-small-cell lung cancer,AFATINIB|ALECTINIB|AMIVANTAMAB|ATEZOLIZUMAB|BEVACIZUMAB|BRIGATINIB|CEMIPLIMAB|CERITINIB|CRIZOTINIB|DABRAFENIB|DACOMITINIB|DURVALUMAB|ENTRECTINIB|ERLOTINIB|GEFITINIB|LORLATINIB|MOBOCERTINIB|NECITUMUMAB|NIVOLUMAB|OSIMERTINIB|PACLITAXEL|PEMBROLIZUMAB|PEMETREXED|PRALSETINIB|RAMUCIRUMAB|SELPERCATINIB|SOTORASIB|TEPOTINIB,MEDICAL ONCOLOGY
   108ÔåÆobesity,LIRAGLUTIDE|NALTREXONE|ORLISTAT|SEMAGLUTIDE|SIBUTRAMINE,ENDOCRINOLOGY
   109ÔåÆoesophageal cancer,NIVOLUMAB,MEDICAL ONCOLOGY
   110ÔåÆosteoarthritis,CELECOXIB,RHEUMATOLOGY
   111ÔåÆosteoporosis,ALENDRONATE|DENOSUMAB|ORAL|ROMOSOZUMAB,RHEUMATOLOGY
   112ÔåÆosteosarcoma,MIFAMURTIDE,MEDICAL ONCOLOGY
   113ÔåÆovarian cancer,BEVACIZUMAB|PACLITAXEL|PEGYLATED|TOPOTECAN|TRABECTEDIN,MEDICAL ONCOLOGY
   114ÔåÆoverweight,RIMONABANT,ENDOCRINOLOGY
   115ÔåÆpancreatic cancer,GEMCITABINE|OLAPARIB|PACLITAXEL|PEGYLATED,MEDICAL ONCOLOGY
   116ÔåÆparoxysmal nocturnal haemoglobinuria,PEGCETACOPLAN|RAVULIZUMAB,CLINICAL HAEMATOLOGY
   117ÔåÆperipheral arterial disease,NAFTIDROFYRYL,VASCULAR SURGERY
   118ÔåÆplaque psoriasis,ADALIMUMAB|APREMILAST|BIMEKIZUMAB|BRODALUMAB|CERTOLIZUMAB|GUSELKUMAB|INFLIXIMAB|IXEKIZUMAB|RISANKIZUMAB|SECUKINUMAB|TILDRAKIZUAMB|USTEKINUMAB,DERMATOLOGY
   119ÔåÆpolycystic kidney disease,TOLVAPTAN,NEPHROLOGY
   120ÔåÆpolycythaemia vera,RUXOLITINIB,CLINICAL HAEMATOLOGY
   121ÔåÆpregnancy,ROUTINE,OBSTETRICS
   122ÔåÆprimary biliary cholangitis,OBETICHOLIC,GASTROENTEROLOGY
   123ÔåÆprimary hypercholesterolaemia,ALIROCUMAB|EVOLOCUMAB,CARDIOLOGY
   124ÔåÆprostate cancer,ABIRATERONE|APALUTAMIDE|CABAZITAXEL|DAROLUTAMIDE|DEGARELIX|DENOSUMAB|DOCETAXEL|ENZALUTAMIDE|OLAPARIB|PADELIPORFIN|RADIUM-|RADIUM|SIPULEUCEL-T,MEDICAL ONCOLOGY
   125ÔåÆpsoriasis,EFALUZIMAB,DERMATOLOGY
   126ÔåÆpsoriatic arthritis,ABATACEPT|ADALIMUMAB|APREMILAST|CERTOLIZUMAB|ETANERCEPT|GOLIMUMAB|GUSELKUMAB|IXEKIZUMAB|RISANKIZUMAB|TOFACITINIB|UPADACITINIB|USTEKINUMAB,RHEUMATOLOGY
   127ÔåÆpulmonary embolism,APIXABAN|DABIGATRAN|EDOXABAN|RIVAROXABAN,THORACIC MEDICINE
   128ÔåÆpulmonary fibrosis,NINTEDANIB|PIRFENIDONE,THORACIC MEDICINE
   129ÔåÆrelapsing multiple sclerosis,OFATUMUMAB,NEUROLOGY
   130ÔåÆrenal cell carcinoma,AVELUMAB|AXITINIB|BEVACIZUMAB|CABOZANTINIB|EVEROLIMUS|LENVATINIB|NIVOLUMAB|PAZOPANIB|PEMBROLIZUMAB|SUNITINIB|TIVOZANIB,MEDICAL ONCOLOGY
   131ÔåÆrenal transplantation,BASILIXIMAB|INDUCTION,NEPHROLOGY
   132ÔåÆretinal vein occlusion,AFLIBERCEPT|DEXAMETHASONE|RANIBIZUMAB,OPHTHALMOLOGY
   133ÔåÆrheumatoid arthritis,ABATACEPT|ADALIMUMAB|ANAKINRA|BARICITINIB|CELECOXIB|CERTOLIZUMAB|ETANERCEPT|FILGOTINIB|GOLIMUMAB|RITUXIMAB|SARILUMAB|TOCILIZUMAB|TOFACITINIB|UPADACITINIB,RHEUMATOLOGY
   134ÔåÆrivaroxaban,ANDEXANET,CARDIOLOGY
   135ÔåÆschizophrenia,AMISULPRIDE|ARIPIPRAZOLE|LOXAPINE,MENTAL HEALTH
   136ÔåÆseizures,CANNABIDIOL,NEUROLOGY
   137ÔåÆsepsis,DROTRECOGIN,INFECTIOUS DISEASES
   138ÔåÆsevere persistent allergic asthma,OMALIZUMAB,THORACIC MEDICINE
   139ÔåÆshort bowel syndrome,TEDUGLUTIDE,GASTROENTEROLOGY
   140ÔåÆsickle cell disease,CRIZANLIZUMAB,CLINICAL HAEMATOLOGY
   141ÔåÆsleep apnoea,PITOLISANT|SOLRIAMFETOL,THORACIC MEDICINE
   142ÔåÆsmoking cessation,NICOTINE|VARENICLINE,THORACIC MEDICINE
   143ÔåÆsoft tissue sarcoma,INTRAVENOUS|NBTXR-|OLARATUMAB,MEDICAL ONCOLOGY
   144ÔåÆspinal muscular atrophy,NUSINERSEN|RISDIPLAM,NEUROLOGY
   145ÔåÆsquamous cell,CETUXIMAB,MEDICAL ONCOLOGY
   146ÔåÆsquamous cell carcinoma,CEMIPLIMAB|NIVOLUMAB|PEMBROLIZUMAB,MEDICAL ONCOLOGY
   147ÔåÆstem cell transplant,MELPHALAN|TREOSULFAN,CLINICAL HAEMATOLOGY
   148ÔåÆstroke,APIXABAN|DABIGATRAN|EDOXABAN|RIVAROXABAN,STROKE MEDICINE
   149ÔåÆsystemic lupus erythematosus,ANIFROLUMAB|ETANERCEPT,RHEUMATOLOGY
   150ÔåÆsystemic mastocytosis,MIDOSTAURIN,CLINICAL HAEMATOLOGY
   151ÔåÆthrombocytopenic purpura,ELTROMBOPAG|ROMIPLOSTIM,CLINICAL HAEMATOLOGY
   152ÔåÆthrombotic thrombocytopenic purpura,CAPLACIZUMAB,CLINICAL HAEMATOLOGY
   153ÔåÆthyroid cancer,CABOZANTINIB|LENVATINIB|SELPERCATINIB|VANDETANIB,MEDICAL ONCOLOGY
   154ÔåÆtophaceous gout,PEGLOTICASE,RHEUMATOLOGY
   155ÔåÆtransitional cell carcinoma,VINFLUNINE,MEDICAL ONCOLOGY
   156ÔåÆtuberous sclerosis,CANNABIDIOL,NEUROLOGY
   157ÔåÆtype 1 diabetes,CONTINUOUS|DAPAGLIFLOZIN|INSULIN|SOTAGLIFLOZIN,DIABETIC MEDICINE
   158ÔåÆtype 2 diabetes,CANAGLIFLOZIN|CONTINUOUS|DAPAGLIFLOZIN|EMPAGLIFLOZIN|ERTUGLIFLOZIN|EXENATIDE|FINERENONE|INSULIN|LIRAGLUTIDE|PIOGLITAZONE|ROSIGLITAZONE,DIABETIC MEDICINE
   159ÔåÆulcerative colitis,ADALIMUMAB|INFLIXIMAB|FILGOTINIB|OZANIMOD|TOFACITINIB|UPADACITINIB|USTEKINUMAB|VEDOLIZUMAB,GASTROENTEROLOGY
   160ÔåÆurothelial carcinoma,ATEZOLIZUMAB|PEMBROLIZUMAB,MEDICAL ONCOLOGY
   161ÔåÆurticaria,OMALIZUMAB,DERMATOLOGY
   162ÔåÆuterine fibroids,RELUGOLIX,GYNAECOLOGY
   163ÔåÆuveitis,ADALIMUMAB|FLUOCINOLONE,OPHTHALMOLOGY
   164ÔåÆvascular disease,MODIFIED-RELEASE|CLOPIDOGREL,VASCULAR SURGERY
   165ÔåÆvasculitis,RITUXIMAB,RHEUMATOLOGY
   166ÔåÆvenous thromboembolism,APIXABAN|DABIGATRAN|RIVAROXABAN,CLINICAL HAEMATOLOGY
   167ÔåÆ

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

Search_Term,CleanedDrugName,PrimaryDirectorate
acute coronary syndrome,ABCIXIMAB|CLOPIDOGREL|PRASUGREL|RIVAROXABAN|TICAGRELOR,CARDIOLOGY
acute lymphoblastic leukaemia,BLINATUMOMAB|DASATINIB|INOTUZUMAB|PEGASPARGASE|PONATINIB|TISAGENLECLEUCEL,CLINICAL HAEMATOLOGY
acute myeloid leukaemia,AZACITIDINE|DECITABINE|GEMTUZUMAB|GILTERITINIB|GLASDEGIB|LIPOSOMAL|MIDOSTAURIN|ORAL|VENETOCLAX,CLINICAL HAEMATOLOGY
acute promyelocytic leukaemia,ARSENIC|GEMTUZUMAB,CLINICAL HAEMATOLOGY
allergic asthma,OMALIZUMAB,THORACIC MEDICINE
allergic rhinitis,SQ,ENT
alzheimer's disease,DONEPEZIL,NEUROLOGY
amyloidosis,VUTRISIRAN,CLINICAL HAEMATOLOGY
anaemia,ERYTHROPOIESIS-STIMULATING|ERYTHROPOIETIN,CLINICAL HAEMATOLOGY
anaplastic large cell lymphoma,BRENTUXIMAB,CLINICAL HAEMATOLOGY
ankylosing spondylitis,ADALIMUMAB|GOLIMUMAB|SECUKINUMAB|UPADACITINIB,RHEUMATOLOGY
apixaban,ANDEXANET,CARDIOLOGY
aplastic anaemia,ELTROMBOPAG,CLINICAL HAEMATOLOGY
arthritis,ETANERCEPT,RHEUMATOLOGY
asthma,BENRALIZUMAB|DUPILUMAB|INHALED|MEPOLIZUMAB|OMALIZUMAB|RESLIZUMAB,THORACIC MEDICINE
atopic dermatitis,ABROCITINIB|ALCLOMETASONE|BARICITINIB|CRISABOROLE|DUPILUMAB|PIMECROLIMUS,DERMATOLOGY
atrial fibrillation,APIXABAN|DABIGATRAN|DRONEDARONE|EDOXABAN|RIVAROXABAN|VERNAKALANT,CARDIOLOGY
attention deficit hyperactivity disorder,ATOMOXETINE,MENTAL HEALTH
attention-deficit hyperactivity disorder,METHYLPHENIDATE,MENTAL HEALTH
axial spondyloarthritis,ADALIMUMAB|GOLIMUMAB|IXEKIZUMAB|SECUKINUMAB|UPADACITINIB,RHEUMATOLOGY
basal cell carcinoma,VISMODEGIB,DERMATOLOGY
bipolar disorder,LOXAPINE|OLANZAPINE,MENTAL HEALTH
bladder,MIRABEGRON,MEDICAL ONCOLOGY
brca,OLAPARIB,MEDICAL ONCOLOGY
breast cancer,ABEMACICLIB|ALPELISIB|ANASTROZOLE|ATEZOLIZUMAB|BEVACIZUMAB|CAPECITABINE|DENOSUMAB|DOCETAXEL|ERIBULIN|EVEROLIMUS|FULVESTRANT|GEMCITABINE|INTRABEAM|LAPATINIB|NERATINIB|OLAPARIB|PACLITAXEL|PALBOCICLI|PALBOCICLIB|PEMBROLIZUMAB|PERTUZUMAB|RIBOCICLIB|SACITUZUMAB|TRASTUZUMAB|TUCATINIB|VINORELBINE,MEDICAL ONCOLOGY
cardiomyopathy,TAFAMIDIS,CARDIOLOGY
cardiovascular disease,ATORVASTATIN,CARDIOLOGY
cervical cancer,TOPOTECAN,MEDICAL ONCOLOGY
cholangiocarcinoma,PEMIGATINIB,MEDICAL ONCOLOGY
choroidal neovascularisation,AFLIBERCEPT|RANIBIZUMAB,OPHTHALMOLOGY
chronic kidney disease,DAPAGLIFLOZIN|IMLIFIDASE|ROXADUSTAT,NEPHROLOGY
chronic liver disease,AVATROMBOPAG|LUSUTROMBOPAG,GASTROENTEROLOGY
chronic lymphocytic leukaemia,ACALABRUTINIB|BENDAMUSTINE|DUVELISIB|IBRUTINIB|IDELALISIB|OBINUTUZUMAB|OFATUMUMAB|RITUXIMAB|VENETOCLAX,CLINICAL HAEMATOLOGY
chronic myeloid leukaemia,ASCIMINIB|BOSUTINIB|STANDARD-DOSE|DASATINIB|DASITINIB|NILOTINIB|PONATINIB,CLINICAL HAEMATOLOGY
chronic obstructive pulmonary disease,ROFLUMILAST,THORACIC MEDICINE
colon cancer,CAPECITABINE,MEDICAL ONCOLOGY
colorectal cancer,BEVACIZUMAB|CAPECITABINE|IRINOTECAN,MEDICAL ONCOLOGY
constipation,LUBIPROSTONE|METHYLNALTREXONE|NALDEMEDINE|NALOXEGOL|PRUCALOPRIDE,GASTROENTEROLOGY
covid-19,NIRMATRELVIR,INFECTIOUS DISEASES
crohn's disease,INFLIXIMAB|VEDOLIZUMAB,GASTROENTEROLOGY
cutaneous t-cell lymphoma,BRENTUXIMAB|CHLORMETHINE,CLINICAL HAEMATOLOGY
cystic fibrosis,COLISTIMETHATE|LUMACAFTOR|MANNITOL,THORACIC MEDICINE
cytomegalovirus,LETERMOVIR|MARIBAVIR,INFECTIOUS DISEASES
deep vein thrombosis,APIXABAN|DABIGATRAN|EDOXABAN|RIVAROXABAN,VASCULAR SURGERY
depression,ESKETAMINE,MENTAL HEALTH
diabetes,ERTUGLIFLOZIN|INHALED|AFLIBERCEPT|BROLUCIZUMAB|DEXAMETHASONE|FARICIMAB|FLUOCINOLONE|RANIBIZUMAB,DIABETIC MEDICINE
diabetes,ERTUGLIFLOZIN|INHALED|AFLIBERCEPT|BROLUCIZUMAB|DEXAMETHASONE|FARICIMAB|FLUOCINOLONE|RANIBIZUMAB,OPHTHALMOLOGY
diabetic retinopathy,RANIBUZIMAB,OPHTHALMOLOGY
diffuse large b-cell lymphoma,AXICABTAGENE|POLATUZUMAB|TISAGENLECLEUCEL,CLINICAL HAEMATOLOGY
dravet syndrome,CANNABIDIOL|FENFLURAMINE,NEUROLOGY
drug misuse,BUPRENORPHINE|NALTREXONE,MENTAL HEALTH
dry eye,CICLOSPORIN,OPHTHALMOLOGY
dyspepsia,LANSOPRAZOLE,GASTROENTEROLOGY
endometrial cancer,DOSTARLIMAB,MEDICAL ONCOLOGY
epilepsy,CENOBAMATE|GABAPENTIN|RETIGABINE,NEUROLOGY
fallopian tube,BEVACIZUMAB|NIRAPARIB|OLAPARIB|RUCAPARIB,MEDICAL ONCOLOGY
follicular lymphoma,DUVELISIB|IDELALISIB|LENALIDOMIDE|OBINUTUZUMAB|RITUXIMAB|TISAGENLECLEUCEL,CLINICAL HAEMATOLOGY
gastric cancer,CAPECITABINE|RAMUCIRUMAB|TRASTUZUMAB|TRIFLURIDINE,MEDICAL ONCOLOGY
gastro-oesophageal junction,NIVOLUMAB|PEMBROLIZUMAB,MEDICAL ONCOLOGY
giant cell arteritis,TOCILIZUMAB,RHEUMATOLOGY
glioma,CARMUSTINE,MEDICAL ONCOLOGY
gout,CANAKINUMAB|FEBUXOSTAT|LESINURAD,RHEUMATOLOGY
graft versus host disease,RUXOLITINIB,CLINICAL HAEMATOLOGY
granulomatosis with polyangiitis,AVACOPAN|MEPOLIZUMAB,RHEUMATOLOGY
growth hormone deficiency,SOMATROPIN,ENDOCRINOLOGY
hand eczema,ALITRETINOIN,DERMATOLOGY
heart failure,DAPAGLIFLOZIN|EMPAGLIFLOZIN|IVABRADINE|SACUBITRIL|VERICIGUAT,CARDIOLOGY
hepatitis b,ADEFOVIR,GASTROENTEROLOGY
hepatitis c,BOCEPREVIR|DACLATASVIR|ELBASVIR|GLECAPREVIR|INTERFERON|LEDIPASVIR|OMBITASVIR|PEGINTERFERON|PEGYLATED|SIMEPREVIR|SOFOSBUVIR|TELAPREVIR,GASTROENTEROLOGY
hepatocellular carcinoma,ATEZOLIZUMAB|CABOZANTINIB|LENVATINIB|RAMUCIRUMAB|REGORAFENIB|SELECTIVE|SORAFENIB,MEDICAL ONCOLOGY
hiv,CABOTEGRAVIR,INFECTIOUS DISEASES
hodgkin lymphoma,BRENTUXIMAB|NIVOLUMAB|PEMBROLIZUMAB,CLINICAL HAEMATOLOGY
hormone receptor,ABEMACICLIB,MEDICAL ONCOLOGY
hypercholesterolaemia,EZETIMIBE,CARDIOLOGY
hyperparathyroidism,CINACALCET|ETELCALCETIDE,ENDOCRINOLOGY
immune thrombocytopenia,AVATROMBOPAG|FOSTAMATINIB,CLINICAL HAEMATOLOGY
influenza,AMANTADINE|ZANAMIVIR|BALOXAVIR,INFECTIOUS DISEASES
insomnia,ZALEPLON,NEUROLOGY
irritable bowel syndrome,ELUXADOLINE,GASTROENTEROLOGY
ischaemic stroke,ALTEPLASE,STROKE MEDICINE
juvenile idiopathic arthritis,ABATECEPT|CANAKINUMAB|TOCILIZUMAB|TOFACITINIB,RHEUMATOLOGY
kidney transplant,BASILIXIMAB,NEPHROLOGY
leukaemia,FLUDARABINE|IMATINIB,CLINICAL HAEMATOLOGY
lung cancer,ATEZOLIZUMAB|DURVALUMAB|GEFITINIB|ORAL|NINTEDANIB,MEDICAL ONCOLOGY
lymphoma,BENDAMUSTINE|CRIZOTINIB|PIXANTRONE|RITUXIMAB,CLINICAL HAEMATOLOGY
macular degeneration,AFLIBERCEPT|BROLUCIZUMAB|FARICIMAB|RANIBIZUMAB,OPHTHALMOLOGY
macular oedema,AFLIBERCEPT|RANIBIZUMAB,OPHTHALMOLOGY
major depressive episodes,AGOMELATINE|VORTIOXETINE,MENTAL HEALTH
malignant melanoma,VEMURAFENIB,MEDICAL ONCOLOGY
malignant pleural mesothelioma,NIVOLUMAB|PEMETREXED,MEDICAL ONCOLOGY
manic episode,ARIPIPRAZOLE,MENTAL HEALTH
mantle cell lymphoma,AUTOLOGOUS|BORTEZOMIB|IBRUTINIB|LENALIDOMIDE|TEMSIROLIMUS,CLINICAL HAEMATOLOGY
melanoma,COBIMETINIB|DABRAFENIB|ENCORAFENIB|IPILIMUMAB|NIVOLUMAB|PEMBROLIZUMAB|TALIMOGENE|TRAMETINIB,MEDICAL ONCOLOGY
merkel cell carcinoma,AVELUMAB,MEDICAL ONCOLOGY
migraine,BOTULINUM|EPTINEZUMAB|ERENUMAB|FREMANEZUMAB|GALCANEZUMAB,NEUROLOGY
motor neurone disease,RILUZOLE,NEUROLOGY
multiple myeloma,BORTEZOMIB|THALIDOMIDE|CARFILZOMIB|DARATUMUMAB|DENOSUMAB|ELOTUZUMAB|ISATUXIMAB|IXAZOMIB|LENALIDOMIDE|PANOBINOSTAT|POMALIDOMIDE|SELINEXOR|TECLISTAMAB,CLINICAL HAEMATOLOGY
multiple sclerosis,ALEMTUZUMAB|BETA|CLADRIBINE|DACLIZUMAB|DIMETHYL|DIROXIMEL|FINGOLIMOD|INTERFERON|NATALIZUMAB|OCRELIZUMAB|OZANIMOD|PEGINTERFERON|PONESIMOD|SIPONIMOD|TERIFLUNOMIDE,NEUROLOGY
myelodysplastic,LENALIDOMIDE|LUSPATERCEPT,CLINICAL HAEMATOLOGY
myelofibrosis,FEDRATINIB|RUXOLITINIB,CLINICAL HAEMATOLOGY
myocardial infarction,ALTEPLASE|BIVALIRUDIN|TICAGRELOR,CARDIOLOGY
myotonia,MEXILETINE,NEUROLOGY
narcolepsy,SOLRIAMFETOL,NEUROLOGY
neuroendocrine tumour,EVEROLIMUS|LUTETIUM,MEDICAL ONCOLOGY
non-small cell lung cancer,ATEZOLIZMAB|DOCETAXEL|ERLOTINIB|PEMETREXED,MEDICAL ONCOLOGY
non-small-cell lung cancer,AFATINIB|ALECTINIB|AMIVANTAMAB|ATEZOLIZUMAB|BEVACIZUMAB|BRIGATINIB|CEMIPLIMAB|CERITINIB|CRIZOTINIB|DABRAFENIB|DACOMITINIB|DURVALUMAB|ENTRECTINIB|ERLOTINIB|GEFITINIB|LORLATINIB|MOBOCERTINIB|NECITUMUMAB|NIVOLUMAB|OSIMERTINIB|PACLITAXEL|PEMBROLIZUMAB|PEMETREXED|PRALSETINIB|RAMUCIRUMAB|SELPERCATINIB|SOTORASIB|TEPOTINIB,MEDICAL ONCOLOGY
obesity,LIRAGLUTIDE|NALTREXONE|ORLISTAT|SEMAGLUTIDE|SIBUTRAMINE,ENDOCRINOLOGY
oesophageal cancer,NIVOLUMAB,MEDICAL ONCOLOGY
osteoarthritis,CELECOXIB,RHEUMATOLOGY
osteoporosis,ALENDRONATE|DENOSUMAB|ORAL|ROMOSOZUMAB,RHEUMATOLOGY
osteosarcoma,MIFAMURTIDE,MEDICAL ONCOLOGY
ovarian cancer,BEVACIZUMAB|PACLITAXEL|PEGYLATED|TOPOTECAN|TRABECTEDIN,MEDICAL ONCOLOGY
overweight,RIMONABANT,ENDOCRINOLOGY
pancreatic cancer,GEMCITABINE|OLAPARIB|PACLITAXEL|PEGYLATED,MEDICAL ONCOLOGY
paroxysmal nocturnal haemoglobinuria,PEGCETACOPLAN|RAVULIZUMAB,CLINICAL HAEMATOLOGY
peripheral arterial disease,NAFTIDROFYRYL,VASCULAR SURGERY
plaque psoriasis,ADALIMUMAB|APREMILAST|BIMEKIZUMAB|BRODALUMAB|CERTOLIZUMAB|GUSELKUMAB|INFLIXIMAB|IXEKIZUMAB|RISANKIZUMAB|SECUKINUMAB|TILDRAKIZUAMB|USTEKINUMAB,DERMATOLOGY
polycystic kidney disease,TOLVAPTAN,NEPHROLOGY
polycythaemia vera,RUXOLITINIB,CLINICAL HAEMATOLOGY
pregnancy,ROUTINE,OBSTETRICS
primary biliary cholangitis,OBETICHOLIC,GASTROENTEROLOGY
primary hypercholesterolaemia,ALIROCUMAB|EVOLOCUMAB,CARDIOLOGY
prostate cancer,ABIRATERONE|APALUTAMIDE|CABAZITAXEL|DAROLUTAMIDE|DEGARELIX|DENOSUMAB|DOCETAXEL|ENZALUTAMIDE|OLAPARIB|PADELIPORFIN|RADIUM-|RADIUM|SIPULEUCEL-T,MEDICAL ONCOLOGY
psoriasis,EFALUZIMAB,DERMATOLOGY
psoriatic arthritis,ABATACEPT|ADALIMUMAB|APREMILAST|CERTOLIZUMAB|ETANERCEPT|GOLIMUMAB|GUSELKUMAB|IXEKIZUMAB|RISANKIZUMAB|TOFACITINIB|UPADACITINIB|USTEKINUMAB,RHEUMATOLOGY
pulmonary embolism,APIXABAN|DABIGATRAN|EDOXABAN|RIVAROXABAN,THORACIC MEDICINE
pulmonary fibrosis,NINTEDANIB|PIRFENIDONE,THORACIC MEDICINE
relapsing multiple sclerosis,OFATUMUMAB,NEUROLOGY
renal cell carcinoma,AVELUMAB|AXITINIB|BEVACIZUMAB|CABOZANTINIB|EVEROLIMUS|LENVATINIB|NIVOLUMAB|PAZOPANIB|PEMBROLIZUMAB|SUNITINIB|TIVOZANIB,MEDICAL ONCOLOGY
renal transplantation,BASILIXIMAB|INDUCTION,NEPHROLOGY
retinal vein occlusion,AFLIBERCEPT|DEXAMETHASONE|RANIBIZUMAB,OPHTHALMOLOGY
rheumatoid arthritis,ABATACEPT|ADALIMUMAB|ANAKINRA|BARICITINIB|CELECOXIB|CERTOLIZUMAB|ETANERCEPT|FILGOTINIB|GOLIMUMAB|RITUXIMAB|SARILUMAB|TOCILIZUMAB|TOFACITINIB|UPADACITINIB,RHEUMATOLOGY
rivaroxaban,ANDEXANET,CARDIOLOGY
schizophrenia,AMISULPRIDE|ARIPIPRAZOLE|LOXAPINE,MENTAL HEALTH
seizures,CANNABIDIOL,NEUROLOGY
sepsis,DROTRECOGIN,INFECTIOUS DISEASES
severe persistent allergic asthma,OMALIZUMAB,THORACIC MEDICINE
short bowel syndrome,TEDUGLUTIDE,GASTROENTEROLOGY
sickle cell disease,CRIZANLIZUMAB,CLINICAL HAEMATOLOGY
sleep apnoea,PITOLISANT|SOLRIAMFETOL,THORACIC MEDICINE
smoking cessation,NICOTINE|VARENICLINE,THORACIC MEDICINE
soft tissue sarcoma,INTRAVENOUS|NBTXR-|OLARATUMAB,MEDICAL ONCOLOGY
spinal muscular atrophy,NUSINERSEN|RISDIPLAM,NEUROLOGY
squamous cell,CETUXIMAB,MEDICAL ONCOLOGY
squamous cell carcinoma,CEMIPLIMAB|NIVOLUMAB|PEMBROLIZUMAB,MEDICAL ONCOLOGY
stem cell transplant,MELPHALAN|TREOSULFAN,CLINICAL HAEMATOLOGY
stroke,APIXABAN|DABIGATRAN|EDOXABAN|RIVAROXABAN,STROKE MEDICINE
systemic lupus erythematosus,ANIFROLUMAB|ETANERCEPT,RHEUMATOLOGY
systemic mastocytosis,MIDOSTAURIN,CLINICAL HAEMATOLOGY
thrombocytopenic purpura,ELTROMBOPAG|ROMIPLOSTIM,CLINICAL HAEMATOLOGY
thrombotic thrombocytopenic purpura,CAPLACIZUMAB,CLINICAL HAEMATOLOGY
thyroid cancer,CABOZANTINIB|LENVATINIB|SELPERCATINIB|VANDETANIB,MEDICAL ONCOLOGY
tophaceous gout,PEGLOTICASE,RHEUMATOLOGY
transitional cell carcinoma,VINFLUNINE,MEDICAL ONCOLOGY
tuberous sclerosis,CANNABIDIOL,NEUROLOGY
type 1 diabetes,CONTINUOUS|DAPAGLIFLOZIN|INSULIN|SOTAGLIFLOZIN,DIABETIC MEDICINE
type 2 diabetes,CANAGLIFLOZIN|CONTINUOUS|DAPAGLIFLOZIN|EMPAGLIFLOZIN|ERTUGLIFLOZIN|EXENATIDE|FINERENONE|INSULIN|LIRAGLUTIDE|PIOGLITAZONE|ROSIGLITAZONE,DIABETIC MEDICINE
ulcerative colitis,ADALIMUMAB|INFLIXIMAB|FILGOTINIB|OZANIMOD|TOFACITINIB|UPADACITINIB|USTEKINUMAB|VEDOLIZUMAB,GASTROENTEROLOGY
urothelial carcinoma,ATEZOLIZUMAB|PEMBROLIZUMAB,MEDICAL ONCOLOGY
urticaria,OMALIZUMAB,DERMATOLOGY
uterine fibroids,RELUGOLIX,GYNAECOLOGY
uveitis,ADALIMUMAB|FLUOCINOLONE,OPHTHALMOLOGY
vascular disease,MODIFIED-RELEASE|CLOPIDOGREL,VASCULAR SURGERY
vasculitis,RITUXIMAB,RHEUMATOLOGY
venous thromboembolism,APIXABAN|DABIGATRAN|RIVAROXABAN,CLINICAL HAEMATOLOGY