{"type":"system","subtype":"init","cwd":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign","session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","tools":["Task","TaskOutput","Bash","Glob","Grep","ExitPlanMode","Read","Edit","Write","NotebookEdit","WebFetch","TodoWrite","WebSearch","TaskStop","AskUserQuestion","Skill","EnterPlanMode","ToolSearch","mcp__snowflake-mcp__test_connection","mcp__snowflake-mcp__list_databases","mcp__snowflake-mcp__list_schemas","mcp__snowflake-mcp__list_tables","mcp__snowflake-mcp__list_views","mcp__snowflake-mcp__describe_table","mcp__snowflake-mcp__read_data","mcp__snowflake-mcp__get_system_health","mcp__snowflake-mcp__describe_query","mcp__snowflake-mcp__execute_async","mcp__snowflake-mcp__get_query_status","mcp__snowflake-mcp__get_async_results","mcp__snowflake-mcp__list_async_queries","mcp__snowflake-mcp__read_data_paginated","mcp__snowflake-mcp__read_data_pandas"],"mcp_servers":[{"name":"Context7","status":"failed"},{"name":"snowflake-mcp","status":"connected"}],"model":"claude-opus-4-6","permissionMode":"bypassPermissions","slash_commands":["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"],"apiKeySource":"none","claude_code_version":"2.1.32","output_style":"default","agents":["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"],"skills":["keybindings-help","debug","frontend-design"],"plugins":[],"uuid":"a4537d3e-07f4-4452-a1ae-13d33ed69e77"}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01Kg3naBhMrg2SP4UXU7JM8q","type":"message","role":"assistant","content":[{"type":"text","text":"\n\nI'll start by reading the required files in order to understand the current state of the project."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":42290,"cache_read_input_tokens":27385,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":42290},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"a2546296-b3ff-4d88-bbe1-c78775873ed7"}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01Kg3naBhMrg2SP4UXU7JM8q","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01ApoKpNASj2XiWMzWbbqNjF","name":"Read","input":{"file_path":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\progress.txt"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":42290,"cache_read_input_tokens":27385,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":42290},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"1f47b735-1596-42b9-90b2-77b1497fdd86"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01ApoKpNASj2XiWMzWbbqNjF","type":"tool_result","content":" 1# Progress Log - Drug-Aware Indication Matching\n 2\n 3## Project Context\n 4\n 5This project extends the indication-based pathway charts (Phase 1-5 complete) with drug-aware matching.\n 6\n 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.\n 8\n 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.\n 10\n 11## Key Data/Patterns\n 12\n 13### DimSearchTerm.csv\n 14- Located at `data/DimSearchTerm.csv`\n 15- Columns: Search_Term, CleanedDrugName (pipe-separated), PrimaryDirectorate\n 16- ~165 rows mapping clinical conditions to drug name fragments\n 17- Drug fragments are substrings that match standardized drug names from HCD data\n 18- Some entries have generic fragments: INHALED, CONTINUOUS, STANDARD-DOSE, PEGYLATED\n 19\n 20### Current get_patient_indication_groups() in diagnosis_lookup.py\n 21- Uses CLUSTER_MAPPING_SQL as CTE in Snowflake query\n 22- Returns ONLY the most recent match per patient (QUALIFY ROW_NUMBER() = 1)\n 23- Needs to return ALL matching Search_Terms per patient (remove QUALIFY)\n 24- Batches 500 patients per query\n 25\n 26### Modified UPID approach\n 27- Current: UPID = Provider Code[:3] + PersonKey (e.g., \"RMV12345\")\n 28- New: UPID = original + \"|\" + search_term (e.g., \"RMV12345|rheumatoid arthritis\")\n 29- The pipe delimiter \"|\" is safe because existing UPIDs are alphanumeric\n 30- generate_icicle_chart_indication() treats UPID as an opaque identifier  modified UPIDs work transparently\n 31- The \" - \" delimiter in pathway ids is used for hierarchy levels, not within UPIDs\n 32\n 33### PseudoNHSNoLinked mapping\n 34- HCD data has PseudoNHSNoLinked column that matches PatientPseudonym in GP records\n 35- PersonKey is provider-specific local ID  do NOT use for GP matching\n 36- One PseudoNHSNoLinked can map to multiple UPIDs (multi-provider patients)\n 37- GP match lookup: PseudoNHSNoLinked  list of matched Search_Terms\n 38\n 39### Drug matching logic\n 40- For each HCD row (UPID + Drug Name):\n 41 1. Get patient's GP-matched Search_Terms with code_frequency (via PseudoNHSNoLinked)\n 42 2. Get which Search_Terms list this drug (from DimSearchTerm.csv)\n 43 3. Intersection = valid indications\n 44 4. If 1: use it. If multiple: pick highest code_frequency (most GP coding = most likely indication). If 0: fallback to directory.\n 45- Modified UPID groups drugs under same indication together naturally\n 46- code_frequency = COUNT(*) of matching SNOMED codes per Search_Term per patient in GP records\n 47- GP code time range: only count codes from MIN(Intervention Date) onwards (the HCD data window)\n 48 - Reduces noise from old/irrelevant diagnoses, makes frequency more meaningful\n 49 - Pass earliest_hcd_date as parameter to get_patient_indication_groups()\n 50- Tiebreaker rationale: 47 RA codes vs 2 crohn's codes  RA is clearly the active condition\n 51\n 52### Known edge cases\n 53- Some DimSearchTerm drug fragments are generic (INHALED, ORAL, CONTINUOUS)\n 54 - These could match broadly but are constrained by GP diagnosis requirement\n 55- A patient visiting multiple providers has multiple UPIDs\n 56 - Each UPID gets its own drug-indication matching independently\n 57- Same Search_Term appears twice in DimSearchTerm.csv with different directorates\n 58 - e.g., \"diabetes\"  DIABETIC MEDICINE and OPHTHALMOLOGY\n 59 - For indication charts, we use Search_Term not directorate, so this is fine\n 60\n 61## Iteration Log\n 62\n 63## Iteration 1  2026-02-05\n 64### Task: 1.3  Build drug-to-Search_Term lookup from DimSearchTerm.csv\n 65### Why this task:\n 66- First iteration, chose Phase 1 foundations. Task 1.2 (CSV loading) is self-contained and testable locally without Snowflake.\n 67- Task 1.1 (Snowflake query update) can't be verified without a live connection  better to do 1.2 first.\n 68- Both 1.1 and 1.2 are independent, so order doesn't matter for dependencies.\n 69### Status: COMPLETE\n 70### What was done:\n 71- Added `load_drug_indication_mapping()` to `diagnosis_lookup.py`:\n 72 - Loads `data/DimSearchTerm.csv`, builds two dicts:\n 73 - `fragment_to_search_terms`: drug fragment (UPPER)  list of Search_Terms\n 74 - `search_term_to_fragments`: search_term  list of drug fragments (UPPER)\n 75 - Handles duplicate Search_Terms (e.g., \"diabetes\" rows combined)\n 76 - Result: 164 Search_Terms, 346 drug fragments\n 77- Added `get_search_terms_for_drug()` to `diagnosis_lookup.py`:\n 78 - Returns all Search_Terms whose drug fragments are substrings of the drug name (case-insensitive)\n 79 - Named differently from plan's `drug_matches_search_term()`  returns all matches at once rather than single boolean, more practical for Phase 2\n 80- Updated `__all__` exports\n 81### Validation results:\n 82- Tier 1 (Code): py_compile passed, import check passed\n 83- Tier 2 (Data): ADALIMUMAB  7 indications (including axial spondyloarthritis, rheumatoid arthritis), OMALIZUMAB  4 indications (asthma, allergic asthma, etc.), PEGYLATED LIPOSOMAL DOXORUBICIN  4 matches via substring, \"ADALIMUMAB 40MG\" matches correctly with dosage info, diabetes fragments combined from 2 CSV rows\n 84- Tier 3 (Functional): N/A (no UI changes)\n 85### Files changed:\n 86- data_processing/diagnosis_lookup.py (added load_drug_indication_mapping, get_search_terms_for_drug)\n 87- IMPLEMENTATION_PLAN.md (marked 1.2 subtasks [x])\n 88### Committed: 0779df7 \"feat: add drug-to-indication mapping from DimSearchTerm.csv (Task 1.3)\"\n 89### Patterns discovered:\n 90- DimSearchTerm.csv has 164 unique Search_Terms (not 165 as noted) because diabetes appears twice with different directorates but same Search_Term\n 91- Some drug fragments are very generic: INHALED, CONTINUOUS, ORAL, STANDARD-DOSE, INTRAVENOUS, PEGYLATED, ROUTINE, INDUCTION  these will match broadly but are constrained by the GP diagnosis requirement in Phase 2\n 92- Function signatures for Phase 2: `get_search_terms_for_drug(drug_name, search_term_to_fragments)` returns list[str]  use this to get candidate indications per drug\n 93### Next iteration should:\n 94- Work on Task 1.2: Merge asthma Search_Terms in CLUSTER_MAPPING_SQL and load_drug_indication_mapping()\n 95 - Merge \"allergic asthma\", \"asthma\", \"severe persistent allergic asthma\"  \"asthma\"\n 96 - Keep \"urticaria\" separate\n 97 - This is self-contained and testable locally\n 98- OR work on Task 1.1: Update `get_patient_indication_groups()` to return ALL matches with code_frequency\n 99 - The current query at line ~1352 of diagnosis_lookup.py uses `QUALIFY ROW_NUMBER() OVER (PARTITION BY pc.\"PatientPseudonym\" ORDER BY pc.\"EventDateTime\" DESC) = 1`  this must be replaced with GROUP BY + COUNT(*)\n 100 - Add `earliest_hcd_date` parameter to restrict GP codes to HCD data window\n 101 - Return columns: PatientPseudonym, Search_Term, code_frequency (not EventDateTime)\n 102- OR if Snowflake isn't available to test 1.1, skip to Task 2.1 (assign_drug_indications function) which can be built and tested with mock data\n 103### Blocked items:\n 104- None\n 105\n 106## Iteration 2  2026-02-05\n 107### Task: 1.2  Merge related asthma Search_Terms in CLUSTER_MAPPING_SQL\n 108### Why this task:\n 109- Previous iteration recommended this as the next task (self-contained, testable locally)\n 110- Both CLUSTER_MAPPING_SQL and load_drug_indication_mapping() need consistent Search_Term names\n 111- Must be done before Task 1.1 (Snowflake query) to ensure GP lookups return \"asthma\" not \"allergic asthma\"\n 112### Status: COMPLETE\n 113### What was done:\n 114- Updated CLUSTER_MAPPING_SQL: changed 'allergic asthma'  'asthma' (AST_COD) and 'severe persistent allergic asthma'  'asthma' (SEVAST_COD)\n 115 - Now 3 rows for 'asthma': AST_COD, eFI2_Asthma, SEVAST_COD\n 116 - urticaria (XSAL_COD) stays separate\n 117- Added SEARCH_TERM_MERGE_MAP constant: {\"allergic asthma\": \"asthma\", \"severe persistent allergic asthma\": \"asthma\"}\n 118- Updated load_drug_indication_mapping() to apply SEARCH_TERM_MERGE_MAP when loading CSV\n 119 - Normalizes Search_Term before accumulating fragments\n 120 - Drug fragments from all 3 original rows combined under \"asthma\" key\n 121- Exported SEARCH_TERM_MERGE_MAP in __all__\n 122### Validation results:\n 123- Tier 1 (Code): py_compile passed, import check passed\n 124- Tier 2 (Data):\n 125 - \"asthma\" fragments: OMALIZUMAB, BENRALIZUMAB, DUPILUMAB, INHALED, MEPOLIZUMAB, RESLIZUMAB (complete combined list)\n 126 - \"allergic asthma\" no longer exists as separate key\n 127 - \"severe persistent allergic asthma\" no longer exists as separate key\n 128 - \"urticaria\"  ['OMALIZUMAB']  correctly separate\n 129 - OMALIZUMAB maps to: ['asthma', 'urticaria']  correct\n 130 - Total Search_Terms: 162 (was 164, 3 asthma entries  1)\n 131 - Total fragments: 346 (unchanged)\n 132- Tier 3 (Functional): N/A (no UI changes)\n 133### Files changed:\n 134- data_processing/diagnosis_lookup.py (CLUSTER_MAPPING_SQL, SEARCH_TERM_MERGE_MAP, load_drug_indication_mapping)\n 135- IMPLEMENTATION_PLAN.md (marked 1.2 subtasks [x])\n 136### Committed: b0a8a9d \"feat: merge asthma Search_Term variants in CLUSTER_MAPPING_SQL and drug mapping (Task 1.2)\"\n 137### Patterns discovered:\n 138- SEARCH_TERM_MERGE_MAP is reusable: any future module that receives Search_Terms from Snowflake can apply the same normalization\n 139- The merge approach (normalize at load time) is cleaner than post-hoc deduplication\n 140### Next iteration should:\n 141- Work on Task 1.1: Update `get_patient_indication_groups()` to return ALL matches with code_frequency\n 142 - The current query at ~line 1467 uses `QUALIFY ROW_NUMBER() OVER (PARTITION BY pc.\"PatientPseudonym\" ORDER BY pc.\"EventDateTime\" DESC) = 1`\n 143 - Replace with GROUP BY + COUNT(*) for code_frequency\n 144 - Add `earliest_hcd_date` parameter to restrict GP codes to HCD data window\n 145 - Return columns: PatientPseudonym, Search_Term, code_frequency\n 146 - Empty DataFrame columns should match new return type\n 147 - This requires Snowflake connectivity to fully test, but code changes can be verified with py_compile and import checks\n 148- OR work on Task 2.1: Create assign_drug_indications()  can be built and tested with mock data\n 149 - This is independent of Task 1.1 if you mock the gp_matches_df input\n 150### Blocked items:\n 151- None\n 152\n 153## Iteration 3  2026-02-05\n 154### Task: 1.1  Update get_patient_indication_groups() to return ALL matches with code_frequency\n 155### Why this task:\n 156- Previous iteration recommended this as the next task\n 157- This is the last remaining Phase 1 dependency  Tasks 2.1/2.2 need the GP matches data in the right format (multiple rows per patient with code_frequency)\n 158- Task 1.1 changes the query fundamentals; better to do this before building assign_drug_indications() which consumes the output\n 159### Status: COMPLETE\n 160### What was done:\n 161- Modified `get_patient_indication_groups()` in `diagnosis_lookup.py`:\n 162 1. **Removed** `QUALIFY ROW_NUMBER() OVER (PARTITION BY pc.\"PatientPseudonym\" ORDER BY pc.\"EventDateTime\" DESC) = 1`\n 163 2. **Replaced** with `GROUP BY pc.\"PatientPseudonym\", aic.Search_Term` + `COUNT(*) AS \"code_frequency\"`\n 164 3. **Added** `earliest_hcd_date: Optional[str] = None` parameter\n 165 4. **Added** optional `AND pc.\"EventDateTime\" >= %s` when earliest_hcd_date is provided\n 166 5. **Updated** return columns from `(PatientPseudonym, Search_Term, EventDateTime)` to `(PatientPseudonym, Search_Term, code_frequency)`\n 167 6. **Updated** all empty DataFrame returns to use new column names\n 168 7. **Updated** logging to show multiple-rows-per-patient stats (avg indications per patient)\n 169 8. **Updated** docstring to describe new behavior and parameters\n 170- Backward compatible: `earliest_hcd_date` defaults to `None`, existing callers still work\n 171- Note: caller in `refresh_pathways.py` (line 424-428) does `dict(zip(...))` which will only keep last match per patient with new multi-row format  this will be updated in Task 3.1\n 172### Validation results:\n 173- Tier 1 (Code): py_compile PASSED, import check PASSED, function signature verified\n 174- Tier 2 (Data): Empty DataFrame returns correct columns ['PatientPseudonym', 'Search_Term', 'code_frequency']; live Snowflake test deferred to Phase 3/4\n 175- Tier 3 (Functional): N/A (no UI changes)\n 176### Files changed:\n 177- data_processing/diagnosis_lookup.py (modified get_patient_indication_groups function)\n 178- IMPLEMENTATION_PLAN.md (marked 1.1 subtasks [x])\n 179### Committed: c93417f \"feat: return ALL GP matches with code_frequency in get_patient_indication_groups (Task 1.1)\"\n 180### Patterns discovered:\n 181- The `earliest_hcd_date` parameter is passed as a string in ISO format (YYYY-MM-DD) via Snowflake %s placeholder  Snowflake handles string-to-timestamp comparison implicitly\n 182- The GROUP BY approach naturally deduplicates SNOMED codes within the same Search_Term  a patient with the same SNOMED code recorded 5 times gets code_frequency=5 (reflecting clinical activity intensity)\n 183- params list is built dynamically: `batch_pseudonyms + [earliest_hcd_date]` only when date filter is active\n 184### Next iteration should:\n 185- Work on Task 2.1: Create `assign_drug_indications()` function\n 186 - This is now unblocked since 1.1 is complete (return format is known)\n 187 - Input: HCD df, gp_matches_df (PatientPseudonym, Search_Term, code_frequency), drug_mapping from load_drug_indication_mapping()\n 188 - Output: (modified_df with UPID|search_term, indication_df mapping modified_UPID  Search_Term)\n 189 - Can be built and tested with mock data (no Snowflake needed)\n 190 - Key logic: for each UPID+Drug pair, intersect drug's Search_Terms with patient's GP matches, pick highest code_frequency as tiebreaker\n 191 - The function needs PseudoNHSNoLinked to look up GP matches, so the df must have that column\n 192 - Task 2.2 (tiebreaker logic) can be done within 2.1 or as a follow-up\n 193- The final Phase 1 subtask (1.1 verify with live Snowflake) will be tested during Phase 3/4 integration\n 194### Blocked items:\n 195- Task 1.1 final subtask \"Verify: Query returns more rows\" requires live Snowflake  deferred to Phase 3/4\n 196\n\n\nWhenever 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.\n\n"}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"83a40667-0748-4134-9628-f533332664e4","tool_use_result":{"type":"text","file":{"filePath":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\progress.txt","content":"# Progress Log - Drug-Aware Indication Matching\n\n## Project Context\n\nThis project extends the indication-based pathway charts (Phase 1-5 complete) with drug-aware matching.\n\n**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.\n\n**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.\n\n## Key Data/Patterns\n\n### DimSearchTerm.csv\n- Located at `data/DimSearchTerm.csv`\n- Columns: Search_Term, CleanedDrugName (pipe-separated), PrimaryDirectorate\n- ~165 rows mapping clinical conditions to drug name fragments\n- Drug fragments are substrings that match standardized drug names from HCD data\n- Some entries have generic fragments: INHALED, CONTINUOUS, STANDARD-DOSE, PEGYLATED\n\n### Current get_patient_indication_groups() in diagnosis_lookup.py\n- Uses CLUSTER_MAPPING_SQL as CTE in Snowflake query\n- Returns ONLY the most recent match per patient (QUALIFY ROW_NUMBER() = 1)\n- Needs to return ALL matching Search_Terms per patient (remove QUALIFY)\n- Batches 500 patients per query\n\n### Modified UPID approach\n- Current: UPID = Provider Code[:3] + PersonKey (e.g., \"RMV12345\")\n- New: UPID = original + \"|\" + search_term (e.g., \"RMV12345|rheumatoid arthritis\")\n- The pipe delimiter \"|\" is safe because existing UPIDs are alphanumeric\n- generate_icicle_chart_indication() treats UPID as an opaque identifier  modified UPIDs work transparently\n- The \" - \" delimiter in pathway ids is used for hierarchy levels, not within UPIDs\n\n### PseudoNHSNoLinked mapping\n- HCD data has PseudoNHSNoLinked column that matches PatientPseudonym in GP records\n- PersonKey is provider-specific local ID  do NOT use for GP matching\n- One PseudoNHSNoLinked can map to multiple UPIDs (multi-provider patients)\n- GP match lookup: PseudoNHSNoLinked  list of matched Search_Terms\n\n### Drug matching logic\n- For each HCD row (UPID + Drug Name):\n 1. Get patient's GP-matched Search_Terms with code_frequency (via PseudoNHSNoLinked)\n 2. Get which Search_Terms list this drug (from DimSearchTerm.csv)\n 3. Intersection = valid indications\n 4. If 1: use it. If multiple: pick highest code_frequency (most GP coding = most likely indication). If 0: fallback to directory.\n- Modified UPID groups drugs under same indication together naturally\n- code_frequency = COUNT(*) of matching SNOMED codes per Search_Term per patient in GP records\n- GP code time range: only count codes from MIN(Intervention Date) onwards (the HCD data window)\n - Reduces noise from old/irrelevant diagnoses, makes frequency more meaningful\n - Pass earliest_hcd_date as parameter to get_patient_indication_groups()\n- Tiebreaker rationale: 47 RA codes vs 2 crohn's codes  RA is clearly the active condition\n\n### Known edge cases\n- Some DimSearchTerm drug fragments are generic (INHALED, ORAL, CONTINUOUS)\n - These could match broadly but are constrained by GP diagnosis requirement\n- A patient visiting multiple providers has multiple UPIDs\n - Each UPID gets its own drug-indication matching independently\n- Same Search_Term appears twice in DimSearchTerm.csv with different directorates\n - e.g., \"diabetes\"  DIABETIC MEDICINE and OPHTHALMOLOGY\n - For indication charts, we use Search_Term not directorate, so this is fine\n\n## Iteration Log\n\n## Iteration 1  2026-02-05\n### Task: 1.3  Build drug-to-Search_Term lookup from DimSearchTerm.csv\n### Why this task:\n- First iteration, chose Phase 1 foundations. Task 1.2 (CSV loading) is self-contained and testable locally without Snowflake.\n- Task 1.1 (Snowflake query update) can't be verified without a live connection  better to do 1.2 first.\n- Both 1.1 and 1.2 are independent, so order doesn't matter for dependencies.\n### Status: COMPLETE\n### What was done:\n- Added `load_drug_indication_mapping()` to `diagnosis_lookup.py`:\n - Loads `data/DimSearchTerm.csv`, builds two dicts:\n - `fragment_to_search_terms`: drug fragment (UPPER)  list of Search_Terms\n - `search_term_to_fragments`: search_term  list of drug fragments (UPPER)\n - Handles duplicate Search_Terms (e.g., \"diabetes\" rows combined)\n - Result: 164 Search_Terms, 346 drug fragments\n- Added `get_search_terms_for_drug()` to `diagnosis_lookup.py`:\n - Returns all Search_Terms whose drug fragments are substrings of the drug name (case-insensitive)\n - Named differently from plan's `drug_matches_search_term()`  returns all matches at once rather than single boolean, more practical for Phase 2\n- Updated `__all__` exports\n### Validation results:\n- Tier 1 (Code): py_compile passed, import check passed\n- Tier 2 (Data): ADALIMUMAB  7 indications (including axial spondyloarthritis, rheumatoid arthritis), OMALIZUMAB  4 indications (asthma, allergic asthma, etc.), PEGYLATED LIPOSOMAL DOXORUBICIN  4 matches via substring, \"ADALIMUMAB 40MG\" matches correctly with dosage info, diabetes fragments combined from 2 CSV rows\n- Tier 3 (Functional): N/A (no UI changes)\n### Files changed:\n- data_processing/diagnosis_lookup.py (added load_drug_indication_mapping, get_search_terms_for_drug)\n- IMPLEMENTATION_PLAN.md (marked 1.2 subtasks [x])\n### Committed: 0779df7 \"feat: add drug-to-indication mapping from DimSearchTerm.csv (Task 1.3)\"\n### Patterns discovered:\n- DimSearchTerm.csv has 164 unique Search_Terms (not 165 as noted) because diabetes appears twice with different directorates but same Search_Term\n- Some drug fragments are very generic: INHALED, CONTINUOUS, ORAL, STANDARD-DOSE, INTRAVENOUS, PEGYLATED, ROUTINE, INDUCTION  these will match broadly but are constrained by the GP diagnosis requirement in Phase 2\n- Function signatures for Phase 2: `get_search_terms_for_drug(drug_name, search_term_to_fragments)` returns list[str]  use this to get candidate indications per drug\n### Next iteration should:\n- Work on Task 1.2: Merge asthma Search_Terms in CLUSTER_MAPPING_SQL and load_drug_indication_mapping()\n - Merge \"allergic asthma\", \"asthma\", \"severe persistent allergic asthma\"  \"asthma\"\n - Keep \"urticaria\" separate\n - This is self-contained and testable locally\n- OR work on Task 1.1: Update `get_patient_indication_groups()` to return ALL matches with code_frequency\n - The current query at line ~1352 of diagnosis_lookup.py uses `QUALIFY ROW_NUMBER() OVER (PARTITION BY pc.\"PatientPseudonym\" ORDER BY pc.\"EventDateTime\" DESC) = 1`  this must be replaced with GROUP BY + COUNT(*)\n - Add `earliest_hcd_date` parameter to restrict GP codes to HCD data window\n - Return columns: PatientPseudonym, Search_Term, code_frequency (not EventDateTime)\n- OR if Snowflake isn't available to test 1.1, skip to Task 2.1 (assign_drug_indications function) which can be built and tested with mock data\n### Blocked items:\n- None\n\n## Iteration 2  2026-02-05\n### Task: 1.2  Merge related asthma Search_Terms in CLUSTER_MAPPING_SQL\n### Why this task:\n- Previous iteration recommended this as the next task (self-contained, testable locally)\n- Both CLUSTER_MAPPING_SQL and load_drug_indication_mapping() need consistent Search_Term names\n- Must be done before Task 1.1 (Snowflake query) to ensure GP lookups return \"asthma\" not \"allergic asthma\"\n### Status: COMPLETE\n### What was done:\n- Updated CLUSTER_MAPPING_SQL: changed 'allergic asthma'  'asthma' (AST_COD) and 'severe persistent allergic asthma'  'asthma' (SEVAST_COD)\n - Now 3 rows for 'asthma': AST_COD, eFI2_Asthma, SEVAST_COD\n - urticaria (XSAL_COD) stays separate\n- Added SEARCH_TERM_MERGE_MAP constant: {\"allergic asthma\": \"asthma\", \"severe persistent allergic asthma\": \"asthma\"}\n- Updated load_drug_indication_mapping() to apply SEARCH_TERM_MERGE_MAP when loading CSV\n - Normalizes Search_Term before accumulating fragments\n - Drug fragments from all 3 original rows combined under \"asthma\" key\n- Exported SEARCH_TERM_MERGE_MAP in __all__\n### Validation results:\n- Tier 1 (Code): py_compile passed, import check passed\n- Tier 2 (Data):\n - \"asthma\" fragments: OMALIZUMAB, BENRALIZUMAB, DUPILUMAB, INHALED, MEPOLIZUMAB, RESLIZUMAB (complete combined list)\n - \"allergic asthma\" no longer exists as separate key\n - \"severe persistent allergic asthma\" no longer exists as separate key\n - \"urticaria\"  ['OMALIZUMAB']  correctly separate\n - OMALIZUMAB maps to: ['asthma', 'urticaria']  correct\n - Total Search_Terms: 162 (was 164, 3 asthma entries  1)\n - Total fragments: 346 (unchanged)\n- Tier 3 (Functional): N/A (no UI changes)\n### Files changed:\n- data_processing/diagnosis_lookup.py (CLUSTER_MAPPING_SQL, SEARCH_TERM_MERGE_MAP, load_drug_indication_mapping)\n- IMPLEMENTATION_PLAN.md (marked 1.2 subtasks [x])\n### Committed: b0a8a9d \"feat: merge asthma Search_Term variants in CLUSTER_MAPPING_SQL and drug mapping (Task 1.2)\"\n### Patterns discovered:\n- SEARCH_TERM_MERGE_MAP is reusable: any future module that receives Search_Terms from Snowflake can apply the same normalization\n- The merge approach (normalize at load time) is cleaner than post-hoc deduplication\n### Next iteration should:\n- Work on Task 1.1: Update `get_patient_indication_groups()` to return ALL matches with code_frequency\n - The current query at ~line 1467 uses `QUALIFY ROW_NUMBER() OVER (PARTITION BY pc.\"PatientPseudonym\" ORDER BY pc.\"EventDateTime\" DESC) = 1`\n - Replace with GROUP BY + COUNT(*) for code_frequency\n - Add `earliest_hcd_date` parameter to restrict GP codes to HCD data window\n - Return columns: PatientPseudonym, Search_Term, code_frequency\n - Empty DataFrame columns should match new return type\n - This requires Snowflake connectivity to fully test, but code changes can be verified with py_compile and import checks\n- OR work on Task 2.1: Create assign_drug_indications()  can be built and tested with mock data\n - This is independent of Task 1.1 if you mock the gp_matches_df input\n### Blocked items:\n- None\n\n## Iteration 3  2026-02-05\n### Task: 1.1  Update get_patient_indication_groups() to return ALL matches with code_frequency\n### Why this task:\n- Previous iteration recommended this as the next task\n- This is the last remaining Phase 1 dependency  Tasks 2.1/2.2 need the GP matches data in the right format (multiple rows per patient with code_frequency)\n- Task 1.1 changes the query fundamentals; better to do this before building assign_drug_indications() which consumes the output\n### Status: COMPLETE\n### What was done:\n- Modified `get_patient_indication_groups()` in `diagnosis_lookup.py`:\n 1. **Removed** `QUALIFY ROW_NUMBER() OVER (PARTITION BY pc.\"PatientPseudonym\" ORDER BY pc.\"EventDateTime\" DESC) = 1`\n 2. **Replaced** with `GROUP BY pc.\"PatientPseudonym\", aic.Search_Term` + `COUNT(*) AS \"code_frequency\"`\n 3. **Added** `earliest_hcd_date: Optional[str] = None` parameter\n 4. **Added** optional `AND pc.\"EventDateTime\" >= %s` when earliest_hcd_date is provided\n 5. **Updated** return columns from `(PatientPseudonym, Search_Term, EventDateTime)` to `(PatientPseudonym, Search_Term, code_frequency)`\n 6. **Updated** all empty DataFrame returns to use new column names\n 7. **Updated** logging to show multiple-rows-per-patient stats (avg indications per patient)\n 8. **Updated** docstring to describe new behavior and parameters\n- Backward compatible: `earliest_hcd_date` defaults to `None`, existing callers still work\n- Note: caller in `refresh_pathways.py` (line 424-428) does `dict(zip(...))` which will only keep last match per patient with new multi-row format  this will be updated in Task 3.1\n### Validation results:\n- Tier 1 (Code): py_compile PASSED, import check PASSED, function signature verified\n- Tier 2 (Data): Empty DataFrame returns correct columns ['PatientPseudonym', 'Search_Term', 'code_frequency']; live Snowflake test deferred to Phase 3/4\n- Tier 3 (Functional): N/A (no UI changes)\n### Files changed:\n- data_processing/diagnosis_lookup.py (modified get_patient_indication_groups function)\n- IMPLEMENTATION_PLAN.md (marked 1.1 subtasks [x])\n### Committed: c93417f \"feat: return ALL GP matches with code_frequency in get_patient_indication_groups (Task 1.1)\"\n### Patterns discovered:\n- The `earliest_hcd_date` parameter is passed as a string in ISO format (YYYY-MM-DD) via Snowflake %s placeholder  Snowflake handles string-to-timestamp comparison implicitly\n- The GROUP BY approach naturally deduplicates SNOMED codes within the same Search_Term  a patient with the same SNOMED code recorded 5 times gets code_frequency=5 (reflecting clinical activity intensity)\n- params list is built dynamically: `batch_pseudonyms + [earliest_hcd_date]` only when date filter is active\n### Next iteration should:\n- Work on Task 2.1: Create `assign_drug_indications()` function\n - This is now unblocked since 1.1 is complete (return format is known)\n - Input: HCD df, gp_matches_df (PatientPseudonym, Search_Term, code_frequency), drug_mapping from load_drug_indication_mapping()\n - Output: (modified_df with UPID|search_term, indication_df mapping modified_UPID  Search_Term)\n - Can be built and tested with mock data (no Snowflake needed)\n - Key logic: for each UPID+Drug pair, intersect drug's Search_Terms with patient's GP matches, pick highest code_frequency as tiebreaker\n - The function needs PseudoNHSNoLinked to look up GP matches, so the df must have that column\n - Task 2.2 (tiebreaker logic) can be done within 2.1 or as a follow-up\n- The final Phase 1 subtask (1.1 verify with live Snowflake) will be tested during Phase 3/4 integration\n### Blocked items:\n- Task 1.1 final subtask \"Verify: Query returns more rows\" requires live Snowflake  deferred to Phase 3/4\n","numLines":196,"startLine":1,"totalLines":196}}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01Kg3naBhMrg2SP4UXU7JM8q","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_012JajNLrAdgPZ8g56P1xF6g","name":"Read","input":{"file_path":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\IMPLEMENTATION_PLAN.md"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":42290,"cache_read_input_tokens":27385,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":42290},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"58daf048-327c-4bc9-804c-3a450afdb3ce"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_012JajNLrAdgPZ8g56P1xF6g","type":"tool_result","content":" 1# Implementation Plan - Drug-Aware Indication Matching\n 2\n 3## Project Overview\n 4\n 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.\n 6\n 7### The Problem\n 8\n 9A patient on ADALIMUMAB + OMALIZUMAB currently gets assigned a single indication (e.g., \"rheumatoid arthritis\"  the most recent GP match). But:\n 10- ADALIMUMAB is used for rheumatoid arthritis, axial spondyloarthritis, crohn's disease, etc.\n 11- OMALIZUMAB is used for asthma, allergic asthma, urticaria\n 12\n 13These are different clinical pathways and should be treated as separate treatment journeys.\n 14\n 15### The Solution\n 16\n 17Match each drug to an indication by cross-referencing:\n 181. **GP diagnosis**  which Search_Terms the patient has matching SNOMED codes for\n 192. **Drug mapping**  which Search_Terms list each drug (from `DimSearchTerm.csv`)\n 20\n 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).\n 22\n 23### Key Design Decisions\n 24\n 25| Aspect | Decision |\n 26|--------|----------|\n 27| Drug-indication source | `data/DimSearchTerm.csv`  Search_Term  CleanedDrugName mapping |\n 28| UPID modification | `{original_UPID}\\|{search_term}` for drugs with matched indication |\n 29| GP diagnosis matching | Return ALL matches per patient (not just most recent) |\n 30| Drug matching | Substring match: HCD drug name contains DimSearchTerm fragment |\n 31| Multiple indication matches per drug | Use highest GP code frequency as tiebreaker (COUNT of matching SNOMED codes per Search_Term) |\n 32| GP code time range | Only codes from MIN(Intervention Date) onwards  restricts to HCD data window |\n 33| No indication match | Fallback to directory (same as current behavior) |\n 34| Same patient, different indications | Separate pathways via different modified UPIDs |\n 35\n 36### Examples\n 37\n 38**Patient on ADALIMUMAB + GOLIMUMAB, GP dx: axial spondyloarthritis + asthma**\n 39- axial spondyloarthritis drug list includes both ADALIMUMAB and GOLIMUMAB\n 40-  Both drugs grouped under \"axial spondyloarthritis\", single pathway\n 41- Modified UPID: `RMV12345|axial spondyloarthritis`\n 42\n 43**Patient on ADALIMUMAB + OMALIZUMAB, GP dx: axial spondyloarthritis + asthma**\n 44- axial spondyloarthritis lists ADALIMUMAB but not OMALIZUMAB\n 45- asthma lists OMALIZUMAB but not ADALIMUMAB\n 46-  Two separate pathways:\n 47 - `RMV12345|axial spondyloarthritis` with ADALIMUMAB\n 48 - `RMV12345|asthma` with OMALIZUMAB\n 49\n 50**Patient on ADALIMUMAB, GP dx: rheumatoid arthritis (47 codes) + crohn's disease (2 codes)**\n 51- Both Search_Terms list ADALIMUMAB AND patient has GP dx for both\n 52-  Tiebreaker: highest code frequency  rheumatoid arthritis has 47 matching SNOMED codes vs 2 for crohn's\n 53-  Single pathway under rheumatoid arthritis (more clinical activity = more likely the treatment indication)\n 54\n 55---\n 56\n 57## Phase 1: Update Snowflake Query & Drug Mapping\n 58\n 59### 1.1 Update `get_patient_indication_groups()` to return ALL matches with frequency\n 60- [x] Modify the Snowflake query in `get_patient_indication_groups()` (diagnosis_lookup.py):\n 61 - Remove `QUALIFY ROW_NUMBER() OVER (PARTITION BY ... ORDER BY EventDateTime DESC) = 1`\n 62 - Return ALL matching Search_Terms per patient with code frequency:\n 63 ```sql\n 64 SELECT pc.\"PatientPseudonym\" AS \"PatientPseudonym\",\n 65 aic.Search_Term AS \"Search_Term\",\n 66 COUNT(*) AS \"code_frequency\"\n 67 FROM PrimaryCareClinicalCoding pc\n 68 JOIN AllIndicationCodes aic ON pc.\"SNOMEDCode\" = aic.SNOMEDCode\n 69 WHERE pc.\"PatientPseudonym\" IN (...)\n 70 AND pc.\"EventDateTime\" >= :earliest_hcd_date\n 71 GROUP BY pc.\"PatientPseudonym\", aic.Search_Term\n 72 ```\n 73 - `code_frequency` = number of matching SNOMED codes per Search_Term per patient\n 74 - Higher frequency = more clinical activity = stronger signal for tiebreaker\n 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\n 76- [x] Accept `earliest_hcd_date` parameter in `get_patient_indication_groups()` and pass to query\n 77- [x] Keep batch processing (500 patients per query)\n 78- [x] Update return type: DataFrame now has multiple rows per patient (PatientPseudonym, Search_Term, code_frequency)\n 79- [ ] Verify: Query returns more rows than before (patients with multiple matching diagnoses) *(requires live Snowflake  will be verified in Phase 3/4)*\n 80\n 81### 1.2 Merge related asthma Search_Terms in CLUSTER_MAPPING_SQL\n 82- [x] In `CLUSTER_MAPPING_SQL` (diagnosis_lookup.py), merge these 3 Search_Terms into one `\"asthma\"` entry:\n 83 - `allergic asthma` (Cluster: OMALIZUMAB only)\n 84 - `asthma` (Cluster: BENRALIZUMAB, DUPILUMAB, INHALED, MEPOLIZUMAB, OMALIZUMAB, RESLIZUMAB)\n 85 - `severe persistent allergic asthma` (Cluster: OMALIZUMAB only)\n 86- [x] Map all 3 Cluster_IDs to `Search_Term = 'asthma'` in the CTE VALUES\n 87- [x] `urticaria` (OMALIZUMAB, DERMATOLOGY) stays SEPARATE  do NOT merge with asthma\n 88- [x] Also update `load_drug_indication_mapping()` to apply the same merge when loading DimSearchTerm.csv:\n 89 - Combine drug lists from all 3 entries under a single `\"asthma\"` key\n 90 - Deduplicate drug fragments (OMALIZUMAB appears in all 3)\n 91- [x] Verify: GP code lookup returns `\"asthma\"` (not `\"allergic asthma\"` or `\"severe persistent allergic asthma\"`)\n 92- [x] Verify: Drug mapping for `\"asthma\"` includes full combined drug list: BENRALIZUMAB, DUPILUMAB, INHALED, MEPOLIZUMAB, OMALIZUMAB, RESLIZUMAB\n 93\n 94### 1.3 Build drug-to-Search_Term lookup from DimSearchTerm.csv\n 95- [x] Add function `load_drug_indication_mapping()` to `diagnosis_lookup.py`:\n 96 - Loads `data/DimSearchTerm.csv`\n 97 - Builds dict: `drug_fragment (uppercase)  list[Search_Term]`\n 98 - Also builds reverse: `search_term  list[drug_fragments]`\n 99 - CleanedDrugName is pipe-separated (e.g., \"ADALIMUMAB|GOLIMUMAB|IXEKIZUMAB\")\n 100- [x] Add function `get_search_terms_for_drug(drug_name, search_term_to_fragments) -> list[str]`:\n 101 - Returns all Search_Terms whose drug fragments are substrings of the drug name (case-insensitive)\n 102 - More practical than per-term boolean check  returns all matches at once for Phase 2 use\n 103- [x] Verify: ADALIMUMAB matches \"axial spondyloarthritis\", OMALIZUMAB matches \"asthma\"\n 104\n 105---\n 106\n 107## Phase 2: Drug-Aware Indication Matching Logic\n 108\n 109### 2.1 Create `assign_drug_indications()` function\n 110- [ ] Add to `diagnosis_lookup.py` or `pathway_pipeline.py`:\n 111 ```\n 112 def assign_drug_indications(\n 113 df: pd.DataFrame, # HCD data with UPID, Drug Name columns\n 114 gp_matches_df: pd.DataFrame, # PatientPseudonym  list of matched Search_Terms\n 115 drug_mapping: dict, # From load_drug_indication_mapping()\n 116 ) -> tuple[pd.DataFrame, pd.DataFrame]:\n 117 Returns: (modified_df, indication_df)\n 118 - modified_df: HCD data with UPID replaced by {UPID}|{indication}\n 119 - indication_df: mapping modified_UPID  Search_Term\n 120 ```\n 121- [ ] Logic per UPID + Drug Name pair:\n 122 1. Get patient's GP-matched Search_Terms with code_frequency (from gp_matches_df via PseudoNHSNoLinked)\n 123 2. Get which Search_Terms include this drug (from drug_mapping)\n 124 3. Intersection = valid indications for this drug-patient pair\n 125 4. If 1 match: use it\n 126 5. If multiple matches: use highest code_frequency as tiebreaker (most GP coding activity = most likely treatment indication)\n 127 6. If 0 matches: use fallback directory\n 128- [ ] Modify UPID in df rows: `{original_UPID}|{matched_search_term}`\n 129- [ ] Build indication_df: `{modified_UPID}`  `Search_Term` (or fallback label)\n 130- [ ] Verify: Function compiles, handles edge cases (no GP match, no drug match)\n 131\n 132### 2.2 Handle tiebreaker for multiple indication matches\n 133- [ ] When a drug matches multiple Search_Terms AND patient has GP dx for multiple:\n 134 - Use `code_frequency` from the GP query (COUNT of matching SNOMED codes per Search_Term)\n 135 - Higher code_frequency = more clinical activity for that condition = more likely treatment indication\n 136 - E.g., patient with 47 RA codes and 2 crohn's codes  ADALIMUMAB assigned to RA\n 137 - code_frequency is already returned by the updated query in Task 1.1\n 138- [ ] Verify: Tiebreaker logic correctly picks highest-frequency diagnosis\n 139- [ ] Verify: Tie on frequency (rare but possible) falls back to alphabetical Search_Term for determinism\n 140\n 141---\n 142\n 143## Phase 3: Pipeline Integration\n 144\n 145### 3.1 Update `refresh_pathways.py` indication processing\n 146- [ ] In the `elif current_chart_type == \"indication\":` block:\n 147 1. Call `get_patient_indication_groups()` as before (but now returns ALL matches)\n 148 2. Load drug mapping: `drug_mapping = load_drug_indication_mapping()`\n 149 3. Call `assign_drug_indications(df, gp_matches_df, drug_mapping)`\n 150 4. Use modified_df (with indication-aware UPIDs) for pathway processing\n 151 5. Use indication_df for the indication mapping\n 152- [ ] Pass modified_df (not original df) to `process_indication_pathway_for_date_filter()`\n 153- [ ] Verify: Pipeline compiles, `python -m py_compile cli/refresh_pathways.py`\n 154\n 155### 3.2 Test with dry run\n 156- [ ] Run `python -m cli.refresh_pathways --chart-type indication --dry-run -v`\n 157- [ ] Verify:\n 158 - Modified UPIDs appear in pipeline log (e.g., `RMV12345|rheumatoid arthritis`)\n 159 - Patient counts are reasonable (will be higher than before since same patient can appear under multiple indications)\n 160 - Drug-indication matching is logged (match rate, fallback rate)\n 161 - Pathway hierarchy shows drug-specific grouping under correct indications\n 162\n 163---\n 164\n 165## Phase 4: Full Refresh & Validation\n 166\n 167### 4.1 Full refresh with both chart types\n 168- [ ] Run `python -m cli.refresh_pathways --chart-type all`\n 169- [ ] Verify:\n 170 - Both chart types generate data\n 171 - Directory charts unchanged (no modified UPIDs)\n 172 - Indication charts reflect drug-aware matching\n 173\n 174### 4.2 Validate indication chart correctness\n 175- [ ] Check that drugs under an indication all appear in that Search_Term's drug list\n 176- [ ] Verify that a patient on drugs for different indications creates separate pathway branches\n 177- [ ] Verify that drugs sharing an indication are grouped in the same pathway\n 178- [ ] Log: patient count comparison (old vs new approach)\n 179\n 180### 4.3 Validate Reflex UI\n 181- [ ] Run `python -m reflex compile` to verify app compiles\n 182- [ ] Verify chart type toggle still works\n 183- [ ] Verify indication chart shows correct hierarchy\n 184\n 185---\n 186\n 187## Completion Criteria\n 188\n 189All tasks marked `[x]` AND:\n 190- [ ] App compiles without errors (`reflex compile` succeeds)\n 191- [ ] Both chart types generate pathway data\n 192- [ ] Indication charts show drug-specific indication matching\n 193- [ ] Drugs under the same indication for the same patient are in one pathway\n 194- [ ] Drugs under different indications for the same patient create separate pathways\n 195- [ ] Fallback works for drugs with no indication match\n 196- [ ] Full refresh completes successfully\n 197- [ ] Existing directory charts are unaffected\n 198\n 199---\n 200\n 201## Reference\n 202\n 203### DimSearchTerm.csv Structure\n 204```\n 205Search_Term,CleanedDrugName,PrimaryDirectorate\n 206rheumatoid arthritis,ABATACEPT|ADALIMUMAB|ANAKINRA|BARICITINIB|...,RHEUMATOLOGY\n 207asthma,BENRALIZUMAB|DUPILUMAB|INHALED|MEPOLIZUMAB|OMALIZUMAB|RESLIZUMAB,THORACIC MEDICINE\n 208```\n 209\n 210### Modified UPID Format\n 211```\n 212Original: RMV12345\n 213Modified: RMV12345|rheumatoid arthritis\n 214Fallback: RMV12345|RHEUMATOLOGY (no GP dx)\n 215```\n 216\n 217### Current vs New Indication Flow\n 218```\n 219CURRENT:\n 220 Patient  GP dx (most recent)  single Search_Term  one pathway\n 221\n 222NEW:\n 223 Patient + Drug A  GP dx matching Drug A  Search_Term X\n 224 Patient + Drug B  GP dx matching Drug B  Search_Term Y\n 225  If X == Y: one pathway under X\n 226  If X != Y: two pathways (modified UPIDs)\n 227```\n 228\n 229### Key Files\n 230\n 231| File | Changes |\n 232|------|---------|\n 233| `data_processing/diagnosis_lookup.py` | Update query, add drug mapping functions |\n 234| `data_processing/pathway_pipeline.py` | Possibly minor changes for modified UPIDs |\n 235| `cli/refresh_pathways.py` | Integrate drug-aware matching into pipeline |\n 236| `data/DimSearchTerm.csv` | Reference data (read-only) |\n 237| `analysis/pathway_analyzer.py` | No changes expected (UPID changes are transparent) |\n 238| `pathways_app/pathways_app.py` | No changes expected |\n 239\n\n\nWhenever 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.\n\n"}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"c578eb42-8f02-4ee6-bef1-b47a03445afb","tool_use_result":{"type":"text","file":{"filePath":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\IMPLEMENTATION_PLAN.md","content":"# Implementation Plan - Drug-Aware Indication Matching\n\n## Project Overview\n\nUpdate 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.\n\n### The Problem\n\nA patient on ADALIMUMAB + OMALIZUMAB currently gets assigned a single indication (e.g., \"rheumatoid arthritis\"  the most recent GP match). But:\n- ADALIMUMAB is used for rheumatoid arthritis, axial spondyloarthritis, crohn's disease, etc.\n- OMALIZUMAB is used for asthma, allergic asthma, urticaria\n\nThese are different clinical pathways and should be treated as separate treatment journeys.\n\n### The Solution\n\nMatch each drug to an indication by cross-referencing:\n1. **GP diagnosis**  which Search_Terms the patient has matching SNOMED codes for\n2. **Drug mapping**  which Search_Terms list each drug (from `DimSearchTerm.csv`)\n\nOnly 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).\n\n### Key Design Decisions\n\n| Aspect | Decision |\n|--------|----------|\n| Drug-indication source | `data/DimSearchTerm.csv`  Search_Term  CleanedDrugName mapping |\n| UPID modification | `{original_UPID}\\|{search_term}` for drugs with matched indication |\n| GP diagnosis matching | Return ALL matches per patient (not just most recent) |\n| Drug matching | Substring match: HCD drug name contains DimSearchTerm fragment |\n| Multiple indication matches per drug | Use highest GP code frequency as tiebreaker (COUNT of matching SNOMED codes per Search_Term) |\n| GP code time range | Only codes from MIN(Intervention Date) onwards  restricts to HCD data window |\n| No indication match | Fallback to directory (same as current behavior) |\n| Same patient, different indications | Separate pathways via different modified UPIDs |\n\n### Examples\n\n**Patient on ADALIMUMAB + GOLIMUMAB, GP dx: axial spondyloarthritis + asthma**\n- axial spondyloarthritis drug list includes both ADALIMUMAB and GOLIMUMAB\n-  Both drugs grouped under \"axial spondyloarthritis\", single pathway\n- Modified UPID: `RMV12345|axial spondyloarthritis`\n\n**Patient on ADALIMUMAB + OMALIZUMAB, GP dx: axial spondyloarthritis + asthma**\n- axial spondyloarthritis lists ADALIMUMAB but not OMALIZUMAB\n- asthma lists OMALIZUMAB but not ADALIMUMAB\n-  Two separate pathways:\n - `RMV12345|axial spondyloarthritis` with ADALIMUMAB\n - `RMV12345|asthma` with OMALIZUMAB\n\n**Patient on ADALIMUMAB, GP dx: rheumatoid arthritis (47 codes) + crohn's disease (2 codes)**\n- Both Search_Terms list ADALIMUMAB AND patient has GP dx for both\n-  Tiebreaker: highest code frequency  rheumatoid arthritis has 47 matching SNOMED codes vs 2 for crohn's\n-  Single pathway under rheumatoid arthritis (more clinical activity = more likely the treatment indication)\n\n---\n\n## Phase 1: Update Snowflake Query & Drug Mapping\n\n### 1.1 Update `get_patient_indication_groups()` to return ALL matches with frequency\n- [x] Modify the Snowflake query in `get_patient_indication_groups()` (diagnosis_lookup.py):\n - Remove `QUALIFY ROW_NUMBER() OVER (PARTITION BY ... ORDER BY EventDateTime DESC) = 1`\n - Return ALL matching Search_Terms per patient with code frequency:\n ```sql\n SELECT pc.\"PatientPseudonym\" AS \"PatientPseudonym\",\n aic.Search_Term AS \"Search_Term\",\n COUNT(*) AS \"code_frequency\"\n FROM PrimaryCareClinicalCoding pc\n JOIN AllIndicationCodes aic ON pc.\"SNOMEDCode\" = aic.SNOMEDCode\n WHERE pc.\"PatientPseudonym\" IN (...)\n AND pc.\"EventDateTime\" >= :earliest_hcd_date\n GROUP BY pc.\"PatientPseudonym\", aic.Search_Term\n ```\n - `code_frequency` = number of matching SNOMED codes per Search_Term per patient\n - Higher frequency = more clinical activity = stronger signal for tiebreaker\n - `earliest_hcd_date` = `MIN(Intervention Date)` from the HCD DataFrame  restricts GP codes to the HCD data window, reducing noise from old/irrelevant diagnoses\n- [x] Accept `earliest_hcd_date` parameter in `get_patient_indication_groups()` and pass to query\n- [x] Keep batch processing (500 patients per query)\n- [x] Update return type: DataFrame now has multiple rows per patient (PatientPseudonym, Search_Term, code_frequency)\n- [ ] Verify: Query returns more rows than before (patients with multiple matching diagnoses) *(requires live Snowflake  will be verified in Phase 3/4)*\n\n### 1.2 Merge related asthma Search_Terms in CLUSTER_MAPPING_SQL\n- [x] In `CLUSTER_MAPPING_SQL` (diagnosis_lookup.py), merge these 3 Search_Terms into one `\"asthma\"` entry:\n - `allergic asthma` (Cluster: OMALIZUMAB only)\n - `asthma` (Cluster: BENRALIZUMAB, DUPILUMAB, INHALED, MEPOLIZUMAB, OMALIZUMAB, RESLIZUMAB)\n - `severe persistent allergic asthma` (Cluster: OMALIZUMAB only)\n- [x] Map all 3 Cluster_IDs to `Search_Term = 'asthma'` in the CTE VALUES\n- [x] `urticaria` (OMALIZUMAB, DERMATOLOGY) stays SEPARATE  do NOT merge with asthma\n- [x] Also update `load_drug_indication_mapping()` to apply the same merge when loading DimSearchTerm.csv:\n - Combine drug lists from all 3 entries under a single `\"asthma\"` key\n - Deduplicate drug fragments (OMALIZUMAB appears in all 3)\n- [x] Verify: GP code lookup returns `\"asthma\"` (not `\"allergic asthma\"` or `\"severe persistent allergic asthma\"`)\n- [x] Verify: Drug mapping for `\"asthma\"` includes full combined drug list: BENRALIZUMAB, DUPILUMAB, INHALED, MEPOLIZUMAB, OMALIZUMAB, RESLIZUMAB\n\n### 1.3 Build drug-to-Search_Term lookup from DimSearchTerm.csv\n- [x] Add function `load_drug_indication_mapping()` to `diagnosis_lookup.py`:\n - Loads `data/DimSearchTerm.csv`\n - Builds dict: `drug_fragment (uppercase)  list[Search_Term]`\n - Also builds reverse: `search_term  list[drug_fragments]`\n - CleanedDrugName is pipe-separated (e.g., \"ADALIMUMAB|GOLIMUMAB|IXEKIZUMAB\")\n- [x] Add function `get_search_terms_for_drug(drug_name, search_term_to_fragments) -> list[str]`:\n - Returns all Search_Terms whose drug fragments are substrings of the drug name (case-insensitive)\n - More practical than per-term boolean check  returns all matches at once for Phase 2 use\n- [x] Verify: ADALIMUMAB matches \"axial spondyloarthritis\", OMALIZUMAB matches \"asthma\"\n\n---\n\n## Phase 2: Drug-Aware Indication Matching Logic\n\n### 2.1 Create `assign_drug_indications()` function\n- [ ] Add to `diagnosis_lookup.py` or `pathway_pipeline.py`:\n ```\n def assign_drug_indications(\n df: pd.DataFrame, # HCD data with UPID, Drug Name columns\n gp_matches_df: pd.DataFrame, # PatientPseudonym  list of matched Search_Terms\n drug_mapping: dict, # From load_drug_indication_mapping()\n ) -> tuple[pd.DataFrame, pd.DataFrame]:\n Returns: (modified_df, indication_df)\n - modified_df: HCD data with UPID replaced by {UPID}|{indication}\n - indication_df: mapping modified_UPID  Search_Term\n ```\n- [ ] Logic per UPID + Drug Name pair:\n 1. Get patient's GP-matched Search_Terms with code_frequency (from gp_matches_df via PseudoNHSNoLinked)\n 2. Get which Search_Terms include this drug (from drug_mapping)\n 3. Intersection = valid indications for this drug-patient pair\n 4. If 1 match: use it\n 5. If multiple matches: use highest code_frequency as tiebreaker (most GP coding activity = most likely treatment indication)\n 6. If 0 matches: use fallback directory\n- [ ] Modify UPID in df rows: `{original_UPID}|{matched_search_term}`\n- [ ] Build indication_df: `{modified_UPID}`  `Search_Term` (or fallback label)\n- [ ] Verify: Function compiles, handles edge cases (no GP match, no drug match)\n\n### 2.2 Handle tiebreaker for multiple indication matches\n- [ ] When a drug matches multiple Search_Terms AND patient has GP dx for multiple:\n - Use `code_frequency` from the GP query (COUNT of matching SNOMED codes per Search_Term)\n - Higher code_frequency = more clinical activity for that condition = more likely treatment indication\n - E.g., patient with 47 RA codes and 2 crohn's codes  ADALIMUMAB assigned to RA\n - code_frequency is already returned by the updated query in Task 1.1\n- [ ] Verify: Tiebreaker logic correctly picks highest-frequency diagnosis\n- [ ] Verify: Tie on frequency (rare but possible) falls back to alphabetical Search_Term for determinism\n\n---\n\n## Phase 3: Pipeline Integration\n\n### 3.1 Update `refresh_pathways.py` indication processing\n- [ ] In the `elif current_chart_type == \"indication\":` block:\n 1. Call `get_patient_indication_groups()` as before (but now returns ALL matches)\n 2. Load drug mapping: `drug_mapping = load_drug_indication_mapping()`\n 3. Call `assign_drug_indications(df, gp_matches_df, drug_mapping)`\n 4. Use modified_df (with indication-aware UPIDs) for pathway processing\n 5. Use indication_df for the indication mapping\n- [ ] Pass modified_df (not original df) to `process_indication_pathway_for_date_filter()`\n- [ ] Verify: Pipeline compiles, `python -m py_compile cli/refresh_pathways.py`\n\n### 3.2 Test with dry run\n- [ ] Run `python -m cli.refresh_pathways --chart-type indication --dry-run -v`\n- [ ] Verify:\n - Modified UPIDs appear in pipeline log (e.g., `RMV12345|rheumatoid arthritis`)\n - Patient counts are reasonable (will be higher than before since same patient can appear under multiple indications)\n - Drug-indication matching is logged (match rate, fallback rate)\n - Pathway hierarchy shows drug-specific grouping under correct indications\n\n---\n\n## Phase 4: Full Refresh & Validation\n\n### 4.1 Full refresh with both chart types\n- [ ] Run `python -m cli.refresh_pathways --chart-type all`\n- [ ] Verify:\n - Both chart types generate data\n - Directory charts unchanged (no modified UPIDs)\n - Indication charts reflect drug-aware matching\n\n### 4.2 Validate indication chart correctness\n- [ ] Check that drugs under an indication all appear in that Search_Term's drug list\n- [ ] Verify that a patient on drugs for different indications creates separate pathway branches\n- [ ] Verify that drugs sharing an indication are grouped in the same pathway\n- [ ] Log: patient count comparison (old vs new approach)\n\n### 4.3 Validate Reflex UI\n- [ ] Run `python -m reflex compile` to verify app compiles\n- [ ] Verify chart type toggle still works\n- [ ] Verify indication chart shows correct hierarchy\n\n---\n\n## Completion Criteria\n\nAll tasks marked `[x]` AND:\n- [ ] App compiles without errors (`reflex compile` succeeds)\n- [ ] Both chart types generate pathway data\n- [ ] Indication charts show drug-specific indication matching\n- [ ] Drugs under the same indication for the same patient are in one pathway\n- [ ] Drugs under different indications for the same patient create separate pathways\n- [ ] Fallback works for drugs with no indication match\n- [ ] Full refresh completes successfully\n- [ ] Existing directory charts are unaffected\n\n---\n\n## Reference\n\n### DimSearchTerm.csv Structure\n```\nSearch_Term,CleanedDrugName,PrimaryDirectorate\nrheumatoid arthritis,ABATACEPT|ADALIMUMAB|ANAKINRA|BARICITINIB|...,RHEUMATOLOGY\nasthma,BENRALIZUMAB|DUPILUMAB|INHALED|MEPOLIZUMAB|OMALIZUMAB|RESLIZUMAB,THORACIC MEDICINE\n```\n\n### Modified UPID Format\n```\nOriginal: RMV12345\nModified: RMV12345|rheumatoid arthritis\nFallback: RMV12345|RHEUMATOLOGY (no GP dx)\n```\n\n### Current vs New Indication Flow\n```\nCURRENT:\n Patient  GP dx (most recent)  single Search_Term  one pathway\n\nNEW:\n Patient + Drug A  GP dx matching Drug A  Search_Term X\n Patient + Drug B  GP dx matching Drug B  Search_Term Y\n  If X == Y: one pathway under X\n  If X != Y: two pathways (modified UPIDs)\n```\n\n### Key Files\n\n| File | Changes |\n|------|---------|\n| `data_processing/diagnosis_lookup.py` | Update query, add drug mapping functions |\n| `data_processing/pathway_pipeline.py` | Possibly minor changes for modified UPIDs |\n| `cli/refresh_pathways.py` | Integrate drug-aware matching into pipeline |\n| `data/DimSearchTerm.csv` | Reference data (read-only) |\n| `analysis/pathway_analyzer.py` | No changes expected (UPID changes are transparent) |\n| `pathways_app/pathways_app.py` | No changes expected |\n","numLines":239,"startLine":1,"totalLines":239}}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01Kg3naBhMrg2SP4UXU7JM8q","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01EDTENPSwPVDUcHXJsZypQK","name":"Read","input":{"file_path":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\guardrails.md"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":42290,"cache_read_input_tokens":27385,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":42290},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"408c621d-224b-4b7d-a2bb-f594c94db2d2"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01EDTENPSwPVDUcHXJsZypQK","type":"tool_result","content":" 1# Guardrails\n 2\n 3Known failure patterns. Read EVERY iteration. Follow ALL of these rules.\n 4If you discover a new failure pattern during your work, add it to this file.\n 5\n 6---\n 7\n 8## Drug-Indication Matching Guardrails\n 9\n 10### Match drugs to indications, not just patients to indications\n 11- **When**: Building the indication mapping for pathway charts\n 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.\n 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.\n 14\n 15### Use DimSearchTerm.csv for drug-to-Search_Term mapping\n 16- **When**: Determining which Search_Term a drug belongs to\n 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).\n 18- **Why**: This CSV is the authoritative mapping of which drugs are used for which clinical indications.\n 19\n 20### Use substring matching for drug fragments\n 21- **When**: Matching HCD drug names against DimSearchTerm CleanedDrugName fragments\n 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\".\n 23- **Why**: DimSearchTerm contains both full drug names (ADALIMUMAB) and partial fragments (PEGYLATED, INHALED). Exact match would miss the partial ones.\n 24\n 25### Modified UPID uses pipe delimiter\n 26- **When**: Creating indication-aware UPIDs\n 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.\n 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.\n 29\n 30### Return ALL GP matches per patient, not just most recent\n 31- **When**: Querying Snowflake for patient GP diagnoses\n 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.\n 33- **Why**: A patient may have GP diagnoses for both rheumatoid arthritis AND asthma. We need ALL matches to cross-reference with their drugs.\n 34\n 35### Restrict GP code lookup to HCD data window\n 36- **When**: Building the WHERE clause for the GP record query\n 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()`.\n 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.\n 39\n 40### Tiebreaker: highest GP code frequency when a drug matches multiple indications\n 41- **When**: A single drug maps to multiple Search_Terms AND the patient has GP dx for multiple\n 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.\n 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.\n 44\n 45### Same patient, different indications = separate modified UPIDs\n 46- **When**: A patient's drugs map to different Search_Terms\n 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.\n 48- **Why**: This is the core design  drugs for different indications should create separate treatment pathways, even for the same physical patient.\n 49\n 50### Fallback to directory for unmatched drugs\n 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\n 52- **Rule**: Use fallback format: `{UPID}|{Directory} (no GP dx)`. The indication_df maps this to `\"{Directory} (no GP dx)\"`.\n 53- **Why**: Maintains consistent behavior with the previous approach for patients/drugs without GP diagnosis matches.\n 54\n 55### Merge asthma Search_Terms but keep urticaria separate\n 56- **When**: Working with asthma-related Search_Terms from CLUSTER_MAPPING_SQL or DimSearchTerm.csv\n 57- **Rule**: Merge \"allergic asthma\", \"asthma\", and \"severe persistent allergic asthma\" into a single \"asthma\" Search_Term. Keep \"urticaria\" as a separate Search_Term  do NOT merge it with asthma.\n 58- **Why**: These are clinically the same condition at different severity levels. Splitting them fragments the data. Urticaria is a distinct dermatological condition that happens to share OMALIZUMAB.\n 59\n 60### Don't modify directory chart processing\n 61- **When**: Making changes to the indication matching logic\n 62- **Rule**: Only modify the indication chart path (`elif current_chart_type == \"indication\":`). Directory charts use unmodified UPIDs and directory-based grouping.\n 63- **Why**: Directory charts work correctly and should not be affected by indication matching changes.\n 64\n 65---\n 66\n 67## Snowflake Query Guardrails\n 68\n 69### Use PseudoNHSNoLinked for GP record matching\n 70- **When**: Querying GP records (PrimaryCareClinicalCoding) for patient diagnoses\n 71- **Rule**: Use `PseudoNHSNoLinked` column from HCD data, NOT `PersonKey` (LocalPatientID)\n 72- **Why**: PersonKey is provider-specific local ID. Only PseudoNHSNoLinked matches PatientPseudonym in GP records.\n 73\n 74### Embed cluster query as CTE in Snowflake\n 75- **When**: Looking up patient indications during data refresh\n 76- **Rule**: Use the `CLUSTER_MAPPING_SQL` content as a WITH clause in the patient lookup query\n 77- **Why**: This ensures we always use the complete cluster mapping and don't need local storage\n 78\n 79### Quote mixed-case column aliases in Snowflake SQL\n 80- **When**: Writing SELECT queries that return results to Python code\n 81- **Rule**: Use `AS \"ColumnName\"` (quoted) for any column alias you'll access by name in Python\n 82- **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\"`\n 83\n 84### Build indication_df from all unique UPIDs, not PseudoNHSNoLinked\n 85- **When**: Creating the indication mapping DataFrame for pathway processing\n 86- **Rule**: Use `df.drop_duplicates(subset=['UPID'])` not `drop_duplicates(subset=['PseudoNHSNoLinked'])`\n 87- **Why**: A patient visiting multiple providers has multiple UPIDs. Using unique PseudoNHSNoLinked only maps one UPID per patient, leaving others as NaN.\n 88\n 89---\n 90\n 91## Data Processing Guardrails\n 92\n 93### Copy DataFrames in functions that modify columns\n 94- **When**: Writing functions like `prepare_data()` that modify DataFrame columns\n 95- **Rule**: Always `df = df.copy()` at the start of any function that modifies column values on the input DataFrame\n 96- **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.\n 97\n 98### Include chart_type in UNIQUE constraints for pathway_nodes\n 99- **When**: Creating or modifying the pathway_nodes table schema\n 100- **Rule**: The UNIQUE constraint MUST include `chart_type`: `UNIQUE(date_filter_id, chart_type, ids)`\n 101- **Why**: Without `chart_type`, `INSERT OR REPLACE` silently overwrites directory chart nodes when indication chart nodes are inserted.\n 102\n 103### Handle NaN in Directory when building fallback labels\n 104- **When**: Creating fallback indication labels for patients without GP diagnosis match\n 105- **Rule**: Check `pd.notna(directory)` before concatenating to string. Use `\"UNKNOWN (no GP dx)\"` for NaN cases.\n 106- **Why**: NaN handling prevents TypeError and ensures meaningful fallback labels.\n 107\n 108### Use parameterized queries for SQLite\n 109- **When**: Building WHERE clauses with user-selected filters\n 110- **Rule**: Use `?` placeholders and pass params tuple  never string interpolation\n 111- **Why**: Prevents SQL injection and handles special characters in drug/directory names\n 112\n 113### Use existing pathway_analyzer functions\n 114- **When**: Processing pathway data for the icicle chart\n 115- **Rule**: Reuse functions from `analysis/pathway_analyzer.py`  don't reinvent\n 116- **Why**: The existing code handles edge cases (empty groups, statistics calculation, color mapping)\n 117\n 118---\n 119\n 120## Reflex Guardrails\n 121\n 122### Use .to() methods for Var operations in rx.foreach\n 123- **When**: Working with items inside `rx.foreach` render functions\n 124- **Rule**: Use `item.to(int)` for numeric comparisons, `item.to_string()` for text operations\n 125- **Why**: Items from rx.foreach are Var objects, not plain Python values.\n 126\n 127### Use rx.cond for conditional rendering, not Python if\n 128- **When**: Conditionally showing/hiding components or changing styles based on state\n 129- **Rule**: Use `rx.cond(condition, true_component, false_component)`  not Python `if`\n 130- **Why**: Python `if` evaluates at definition time; `rx.cond` evaluates reactively at render time\n 131\n 132---\n 133\n 134## Process Guardrails\n 135\n 136### One task per iteration\n 137- **When**: Temptation to do additional tasks after completing the current one\n 138- **Rule**: Complete ONE task, validate it, commit it, update progress, then stop\n 139- **Why**: Multiple tasks increase error risk and make failures harder to diagnose\n 140\n 141### Never mark complete without validation\n 142- **When**: Task feels \"done\" but hasn't been tested\n 143- **Rule**: All validation tiers must pass before marking `[x]`\n 144- **Why**: \"Feels done\" is not \"is done\"\n 145\n 146### Write explicit handoff notes\n 147- **When**: Every iteration, before stopping\n 148- **Rule**: The \"Next iteration should\" section must contain specific, actionable guidance\n 149- **Why**: The next iteration has zero memory. If you don't write it down, it's lost.\n 150\n 151### Check existing code for patterns\n 152- **When**: Unsure how to implement something\n 153- **Rule**: Look at `pathways_app/pathways_app.py`, `analysis/pathway_analyzer.py`, `cli/refresh_pathways.py`\n 154- **Why**: The existing codebase has solved many quirks already\n 155\n 156\n 165\n\n\nWhenever 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.\n\n"}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"e82516bf-019c-4180-9a5e-a4f0340dbfe7","tool_use_result":{"type":"text","file":{"filePath":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\guardrails.md","content":"# Guardrails\n\nKnown failure patterns. Read EVERY iteration. Follow ALL of these rules.\nIf you discover a new failure pattern during your work, add it to this file.\n\n---\n\n## Drug-Indication Matching Guardrails\n\n### Match drugs to indications, not just patients to indications\n- **When**: Building the indication mapping for pathway charts\n- **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.\n- **Why**: The previous approach assigned ONE indication per patient (most recent GP dx), ignoring which drugs actually treat which conditions. This produced misleading pathways.\n\n### Use DimSearchTerm.csv for drug-to-Search_Term mapping\n- **When**: Determining which Search_Term a drug belongs to\n- **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).\n- **Why**: This CSV is the authoritative mapping of which drugs are used for which clinical indications.\n\n### Use substring matching for drug fragments\n- **When**: Matching HCD drug names against DimSearchTerm CleanedDrugName fragments\n- **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\".\n- **Why**: DimSearchTerm contains both full drug names (ADALIMUMAB) and partial fragments (PEGYLATED, INHALED). Exact match would miss the partial ones.\n\n### Modified UPID uses pipe delimiter\n- **When**: Creating indication-aware UPIDs\n- **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.\n- **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.\n\n### Return ALL GP matches per patient, not just most recent\n- **When**: Querying Snowflake for patient GP diagnoses\n- **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.\n- **Why**: A patient may have GP diagnoses for both rheumatoid arthritis AND asthma. We need ALL matches to cross-reference with their drugs.\n\n### Restrict GP code lookup to HCD data window\n- **When**: Building the WHERE clause for the GP record query\n- **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()`.\n- **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.\n\n### Tiebreaker: highest GP code frequency when a drug matches multiple indications\n- **When**: A single drug maps to multiple Search_Terms AND the patient has GP dx for multiple\n- **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.\n- **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.\n\n### Same patient, different indications = separate modified UPIDs\n- **When**: A patient's drugs map to different Search_Terms\n- **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.\n- **Why**: This is the core design  drugs for different indications should create separate treatment pathways, even for the same physical patient.\n\n### Fallback to directory for unmatched drugs\n- **When**: A drug doesn't match any Search_Term OR the patient has no GP dx for any of the drug's Search_Terms\n- **Rule**: Use fallback format: `{UPID}|{Directory} (no GP dx)`. The indication_df maps this to `\"{Directory} (no GP dx)\"`.\n- **Why**: Maintains consistent behavior with the previous approach for patients/drugs without GP diagnosis matches.\n\n### Merge asthma Search_Terms but keep urticaria separate\n- **When**: Working with asthma-related Search_Terms from CLUSTER_MAPPING_SQL or DimSearchTerm.csv\n- **Rule**: Merge \"allergic asthma\", \"asthma\", and \"severe persistent allergic asthma\" into a single \"asthma\" Search_Term. Keep \"urticaria\" as a separate Search_Term  do NOT merge it with asthma.\n- **Why**: These are clinically the same condition at different severity levels. Splitting them fragments the data. Urticaria is a distinct dermatological condition that happens to share OMALIZUMAB.\n\n### Don't modify directory chart processing\n- **When**: Making changes to the indication matching logic\n- **Rule**: Only modify the indication chart path (`elif current_chart_type == \"indication\":`). Directory charts use unmodified UPIDs and directory-based grouping.\n- **Why**: Directory charts work correctly and should not be affected by indication matching changes.\n\n---\n\n## Snowflake Query Guardrails\n\n### Use PseudoNHSNoLinked for GP record matching\n- **When**: Querying GP records (PrimaryCareClinicalCoding) for patient diagnoses\n- **Rule**: Use `PseudoNHSNoLinked` column from HCD data, NOT `PersonKey` (LocalPatientID)\n- **Why**: PersonKey is provider-specific local ID. Only PseudoNHSNoLinked matches PatientPseudonym in GP records.\n\n### Embed cluster query as CTE in Snowflake\n- **When**: Looking up patient indications during data refresh\n- **Rule**: Use the `CLUSTER_MAPPING_SQL` content as a WITH clause in the patient lookup query\n- **Why**: This ensures we always use the complete cluster mapping and don't need local storage\n\n### Quote mixed-case column aliases in Snowflake SQL\n- **When**: Writing SELECT queries that return results to Python code\n- **Rule**: Use `AS \"ColumnName\"` (quoted) for any column alias you'll access by name in Python\n- **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\"`\n\n### Build indication_df from all unique UPIDs, not PseudoNHSNoLinked\n- **When**: Creating the indication mapping DataFrame for pathway processing\n- **Rule**: Use `df.drop_duplicates(subset=['UPID'])` not `drop_duplicates(subset=['PseudoNHSNoLinked'])`\n- **Why**: A patient visiting multiple providers has multiple UPIDs. Using unique PseudoNHSNoLinked only maps one UPID per patient, leaving others as NaN.\n\n---\n\n## Data Processing Guardrails\n\n### Copy DataFrames in functions that modify columns\n- **When**: Writing functions like `prepare_data()` that modify DataFrame columns\n- **Rule**: Always `df = df.copy()` at the start of any function that modifies column values on the input DataFrame\n- **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.\n\n### Include chart_type in UNIQUE constraints for pathway_nodes\n- **When**: Creating or modifying the pathway_nodes table schema\n- **Rule**: The UNIQUE constraint MUST include `chart_type`: `UNIQUE(date_filter_id, chart_type, ids)`\n- **Why**: Without `chart_type`, `INSERT OR REPLACE` silently overwrites directory chart nodes when indication chart nodes are inserted.\n\n### Handle NaN in Directory when building fallback labels\n- **When**: Creating fallback indication labels for patients without GP diagnosis match\n- **Rule**: Check `pd.notna(directory)` before concatenating to string. Use `\"UNKNOWN (no GP dx)\"` for NaN cases.\n- **Why**: NaN handling prevents TypeError and ensures meaningful fallback labels.\n\n### Use parameterized queries for SQLite\n- **When**: Building WHERE clauses with user-selected filters\n- **Rule**: Use `?` placeholders and pass params tuple  never string interpolation\n- **Why**: Prevents SQL injection and handles special characters in drug/directory names\n\n### Use existing pathway_analyzer functions\n- **When**: Processing pathway data for the icicle chart\n- **Rule**: Reuse functions from `analysis/pathway_analyzer.py`  don't reinvent\n- **Why**: The existing code handles edge cases (empty groups, statistics calculation, color mapping)\n\n---\n\n## Reflex Guardrails\n\n### Use .to() methods for Var operations in rx.foreach\n- **When**: Working with items inside `rx.foreach` render functions\n- **Rule**: Use `item.to(int)` for numeric comparisons, `item.to_string()` for text operations\n- **Why**: Items from rx.foreach are Var objects, not plain Python values.\n\n### Use rx.cond for conditional rendering, not Python if\n- **When**: Conditionally showing/hiding components or changing styles based on state\n- **Rule**: Use `rx.cond(condition, true_component, false_component)`  not Python `if`\n- **Why**: Python `if` evaluates at definition time; `rx.cond` evaluates reactively at render time\n\n---\n\n## Process Guardrails\n\n### One task per iteration\n- **When**: Temptation to do additional tasks after completing the current one\n- **Rule**: Complete ONE task, validate it, commit it, update progress, then stop\n- **Why**: Multiple tasks increase error risk and make failures harder to diagnose\n\n### Never mark complete without validation\n- **When**: Task feels \"done\" but hasn't been tested\n- **Rule**: All validation tiers must pass before marking `[x]`\n- **Why**: \"Feels done\" is not \"is done\"\n\n### Write explicit handoff notes\n- **When**: Every iteration, before stopping\n- **Rule**: The \"Next iteration should\" section must contain specific, actionable guidance\n- **Why**: The next iteration has zero memory. If you don't write it down, it's lost.\n\n### Check existing code for patterns\n- **When**: Unsure how to implement something\n- **Rule**: Look at `pathways_app/pathways_app.py`, `analysis/pathway_analyzer.py`, `cli/refresh_pathways.py`\n- **Why**: The existing codebase has solved many quirks already\n\n\n","numLines":165,"startLine":1,"totalLines":165}}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01Q9w8T9sGf2TQJv2TqA5yEh","type":"message","role":"assistant","content":[{"type":"text","text":"Now checking recent commits and reading the current state of the key file I'll be modifying."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":13169,"cache_read_input_tokens":69675,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":13169},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"2ac940f0-d1c0-4321-b4bf-ec34b9aa6589"}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01Q9w8T9sGf2TQJv2TqA5yEh","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01Ki3HGrDfkiiqwLWBCFdn6f","name":"Bash","input":{"command":"cd \"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\" && git log --oneline -5","description":"Show recent git commits"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":13169,"cache_read_input_tokens":69675,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":13169},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"31754a92-433c-452e-aa05-3c28d3982216"}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01Q9w8T9sGf2TQJv2TqA5yEh","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01CkSRDKo4jEBABQejbBaVJT","name":"Read","input":{"file_path":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\data_processing\\diagnosis_lookup.py"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":13169,"cache_read_input_tokens":69675,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":13169},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"f783b4b1-c868-48de-81b0-ae117cb040a7"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01Ki3HGrDfkiiqwLWBCFdn6f","type":"tool_result","content":"947b87a docs: update progress.txt with Iteration 3 results (Task 1.1)\nc93417f feat: return ALL GP matches with code_frequency in get_patient_indication_groups (Task 1.1)\n4fed0e5 docs: update progress.txt with Iteration 2 results (Task 1.2)\nb0a8a9d feat: merge asthma Search_Term variants in CLUSTER_MAPPING_SQL and drug mapping (Task 1.2)\nc85aae4 docs: update progress.txt with Iteration 1 results (Task 1.2)","is_error":false}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"4b774ed6-446e-4ca0-936d-45ab21c29331","tool_use_result":{"stdout":"947b87a docs: update progress.txt with Iteration 3 results (Task 1.1)\nc93417f feat: return ALL GP matches with code_frequency in get_patient_indication_groups (Task 1.1)\n4fed0e5 docs: update progress.txt with Iteration 2 results (Task 1.2)\nb0a8a9d feat: merge asthma Search_Term variants in CLUSTER_MAPPING_SQL and drug mapping (Task 1.2)\nc85aae4 docs: update progress.txt with Iteration 1 results (Task 1.2)\r","stderr":"","interrupted":false,"isImage":false}}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01CkSRDKo4jEBABQejbBaVJT","type":"tool_result","content":" 1\"\"\"\n 2Diagnosis lookup module for NHS Patient Pathway Analysis.\n 3\n 4Provides functions to validate patient indications by checking GP diagnosis records\n 5against SNOMED cluster codes. Uses the drug-to-cluster mapping from\n 6drug_indication_clusters.csv and queries Snowflake for SNOMED codes and GP records.\n 7\n 8Key workflow:\n 91. Get drug's valid indication clusters from local mapping\n 102. Get all SNOMED codes for those clusters from Snowflake\n 113. Check if patient has any of those SNOMED codes in GP records\n 124. Report indication validation status\n 13\n 14IMPORTANT: HCD activity data indication codes are UNRELIABLE. This module uses\n 15GP/Primary Care data (PrimaryCareClinicalCoding) as the authoritative source.\n 16\"\"\"\n 17\n 18from dataclasses import dataclass, field\n 19from datetime import date, datetime\n 20from pathlib import Path\n 21from typing import Optional, Callable, Any, cast, TYPE_CHECKING\n 22import csv\n 23\n 24if TYPE_CHECKING:\n 25 import pandas as pd\n 26\n 27from core.logging_config import get_logger\n 28from data_processing.database import DatabaseManager, default_db_manager\n 29from data_processing.snowflake_connector import (\n 30 SnowflakeConnector,\n 31 get_connector,\n 32 is_snowflake_available,\n 33 is_snowflake_configured,\n 34 SNOWFLAKE_AVAILABLE,\n 35)\n 36from data_processing.cache import get_cache, is_cache_enabled\n 37\n 38logger = get_logger(__name__)\n 39\n 40\n 41@dataclass\n 42class ClusterSnomedCodes:\n 43 \"\"\"SNOMED codes for a clinical coding cluster.\"\"\"\n 44 cluster_id: str\n 45 cluster_description: str\n 46 snomed_codes: list[str] = field(default_factory=list)\n 47 snomed_descriptions: dict[str, str] = field(default_factory=dict)\n 48\n 49 @property\n 50 def code_count(self) -> int:\n 51 return len(self.snomed_codes)\n 52\n 53\n 54@dataclass\n 55class IndicationValidationResult:\n 56 \"\"\"Result of validating a patient's indication for a drug.\"\"\"\n 57 patient_pseudonym: str\n 58 drug_name: str\n 59 has_valid_indication: bool\n 60 matched_cluster_id: Optional[str] = None\n 61 matched_snomed_code: Optional[str] = None\n 62 matched_snomed_description: Optional[str] = None\n 63 checked_clusters: list[str] = field(default_factory=list)\n 64 total_codes_checked: int = 0\n 65 source: str = \"GP_SNOMED\" # GP_SNOMED | NONE\n 66 error_message: Optional[str] = None\n 67\n 68\n 69@dataclass\n 70class DrugIndicationMatchRate:\n 71 \"\"\"Match rate statistics for a drug's indication validation.\"\"\"\n 72 drug_name: str\n 73 total_patients: int\n 74 patients_with_indication: int\n 75 patients_without_indication: int\n 76 match_rate: float # 0.0 to 1.0\n 77 clusters_checked: list[str] = field(default_factory=list)\n 78 sample_unmatched: list[str] = field(default_factory=list) # Sample patient IDs\n 79\n 80\n 81@dataclass\n 82class DrugSnomedMapping:\n 83 \"\"\"SNOMED code mapping for a drug from ref_drug_snomed_mapping.\"\"\"\n 84 snomed_code: str\n 85 snomed_description: str\n 86 search_term: str\n 87 primary_directorate: str\n 88 indication: str = \"\"\n 89 ta_id: str = \"\"\n 90\n 91\n 92@dataclass\n 93class DirectSnomedMatchResult:\n 94 \"\"\"Result of direct SNOMED code lookup in GP records.\"\"\"\n 95 patient_pseudonym: str\n 96 matched: bool\n 97 snomed_code: Optional[str] = None\n 98 snomed_description: Optional[str] = None\n 99 search_term: Optional[str] = None\n 100 primary_directorate: Optional[str] = None\n 101 event_date: Optional[datetime] = None\n 102 source: str = \"DIRECT_SNOMED\" # DIRECT_SNOMED | NONE\n 103\n 104\n 105@dataclass\n 106class DirectorateAssignment:\n 107 \"\"\"Result of directorate assignment for a patient-drug combination.\"\"\"\n 108 upid: str\n 109 drug_name: str\n 110 directorate: Optional[str]\n 111 search_term: Optional[str] = None\n 112 source: str = \"FALLBACK\" # DIAGNOSIS | FALLBACK\n 113 snomed_code: Optional[str] = None\n 114 event_date: Optional[datetime] = None\n 115\n 116\n 117def get_drug_clusters(\n 118 drug_name: str,\n 119 db_manager: Optional[DatabaseManager] = None\n 120) -> list[dict]:\n 121 \"\"\"\n 122 Get all SNOMED cluster mappings for a drug from local SQLite.\n 123\n 124 Args:\n 125 drug_name: Drug name to look up (case-insensitive)\n 126 db_manager: Optional DatabaseManager (defaults to default_db_manager)\n 127\n 128 Returns:\n 129 List of dicts with keys: drug_name, indication, cluster_id,\n 130 cluster_description, nice_ta_reference\n 131 \"\"\"\n 132 if db_manager is None:\n 133 db_manager = default_db_manager\n 134\n 135 query = \"\"\"\n 136 SELECT drug_name, indication, cluster_id, cluster_description, nice_ta_reference\n 137 FROM ref_drug_indication_clusters\n 138 WHERE UPPER(drug_name) = UPPER(?)\n 139 ORDER BY indication, cluster_id\n 140 \"\"\"\n 141\n 142 try:\n 143 with db_manager.get_connection() as conn:\n 144 cursor = conn.execute(query, (drug_name,))\n 145 rows = cursor.fetchall()\n 146\n 147 results = []\n 148 for row in rows:\n 149 results.append({\n 150 \"drug_name\": row[\"drug_name\"],\n 151 \"indication\": row[\"indication\"],\n 152 \"cluster_id\": row[\"cluster_id\"],\n 153 \"cluster_description\": row[\"cluster_description\"],\n 154 \"nice_ta_reference\": row[\"nice_ta_reference\"],\n 155 })\n 156\n 157 logger.debug(f\"Found {len(results)} cluster mappings for drug '{drug_name}'\")\n 158 return results\n 159\n 160 except Exception as e:\n 161 logger.error(f\"Error getting clusters for drug '{drug_name}': {e}\")\n 162 return []\n 163\n 164\n 165def get_drug_cluster_ids(\n 166 drug_name: str,\n 167 db_manager: Optional[DatabaseManager] = None\n 168) -> list[str]:\n 169 \"\"\"\n 170 Get unique cluster IDs for a drug.\n 171\n 172 Args:\n 173 drug_name: Drug name to look up\n 174 db_manager: Optional DatabaseManager\n 175\n 176 Returns:\n 177 List of unique cluster IDs\n 178 \"\"\"\n 179 clusters = get_drug_clusters(drug_name, db_manager)\n 180 return list(set(c[\"cluster_id\"] for c in clusters))\n 181\n 182\n 183def get_drug_snomed_codes(\n 184 drug_name: str,\n 185 db_manager: Optional[DatabaseManager] = None\n 186) -> list[DrugSnomedMapping]:\n 187 \"\"\"\n 188 Get all SNOMED codes for a drug from local ref_drug_snomed_mapping table.\n 189\n 190 This uses the enriched mapping CSV data loaded into SQLite, which provides\n 191 direct SNOMED-to-drug mappings with Search_Term and PrimaryDirectorate.\n 192\n 193 Args:\n 194 drug_name: Drug name to look up (case-insensitive, matches cleaned_drug_name)\n 195 db_manager: Optional DatabaseManager (defaults to default_db_manager)\n 196\n 197 Returns:\n 198 List of DrugSnomedMapping with snomed_code, snomed_description,\n 199 search_term, primary_directorate, indication, ta_id\n 200 \"\"\"\n 201 if db_manager is None:\n 202 db_manager = default_db_manager\n 203\n 204 query = \"\"\"\n 205 SELECT DISTINCT\n 206 snomed_code,\n 207 snomed_description,\n 208 search_term,\n 209 primary_directorate,\n 210 indication,\n 211 ta_id\n 212 FROM ref_drug_snomed_mapping\n 213 WHERE UPPER(cleaned_drug_name) = UPPER(?)\n 214 OR UPPER(drug_name) = UPPER(?)\n 215 ORDER BY search_term, snomed_code\n 216 \"\"\"\n 217\n 218 try:\n 219 with db_manager.get_connection() as conn:\n 220 cursor = conn.execute(query, (drug_name, drug_name))\n 221 rows = cursor.fetchall()\n 222\n 223 results = []\n 224 for row in rows:\n 225 results.append(DrugSnomedMapping(\n 226 snomed_code=row[\"snomed_code\"],\n 227 snomed_description=row[\"snomed_description\"] or \"\",\n 228 search_term=row[\"search_term\"] or \"\",\n 229 primary_directorate=row[\"primary_directorate\"] or \"\",\n 230 indication=row[\"indication\"] or \"\",\n 231 ta_id=row[\"ta_id\"] or \"\",\n 232 ))\n 233\n 234 logger.debug(f\"Found {len(results)} SNOMED mappings for drug '{drug_name}'\")\n 235 return results\n 236\n 237 except Exception as e:\n 238 logger.error(f\"Error getting SNOMED codes for drug '{drug_name}': {e}\")\n 239 return []\n 240\n 241\n 242def patient_has_indication_direct(\n 243 patient_pseudonym: str,\n 244 drug_snomed_mappings: list[DrugSnomedMapping],\n 245 connector: Optional[SnowflakeConnector] = None,\n 246 before_date: Optional[date] = None,\n 247) -> DirectSnomedMatchResult:\n 248 \"\"\"\n 249 Check if patient has any of the SNOMED codes in their GP records.\n 250\n 251 This is the direct SNOMED lookup - it queries PrimaryCareClinicalCoding\n 252 for exact SNOMED code matches (not via cluster). Returns the most recent\n 253 match by EventDateTime if multiple matches exist.\n 254\n 255 Args:\n 256 patient_pseudonym: Patient's pseudonymised NHS number\n 257 drug_snomed_mappings: List of DrugSnomedMapping from get_drug_snomed_codes()\n 258 connector: Optional SnowflakeConnector (defaults to singleton)\n 259 before_date: Optional date - only check diagnoses before this date\n 260\n 261 Returns:\n 262 DirectSnomedMatchResult with match details (most recent by EventDateTime)\n 263 \"\"\"\n 264 result = DirectSnomedMatchResult(\n 265 patient_pseudonym=patient_pseudonym,\n 266 matched=False,\n 267 source=\"NONE\",\n 268 )\n 269\n 270 if not drug_snomed_mappings:\n 271 return result\n 272\n 273 if not SNOWFLAKE_AVAILABLE:\n 274 logger.warning(\"Snowflake connector not available\")\n 275 return result\n 276\n 277 if not is_snowflake_configured():\n 278 logger.warning(\"Snowflake not configured - cannot check GP records\")\n 279 return result\n 280\n 281 if connector is None:\n 282 connector = get_connector()\n 283\n 284 # Build lookup dict for mapping snomed_code -> (search_term, primary_directorate, snomed_description)\n 285 snomed_lookup = {\n 286 m.snomed_code: (m.search_term, m.primary_directorate, m.snomed_description)\n 287 for m in drug_snomed_mappings\n 288 }\n 289\n 290 # Get unique SNOMED codes\n 291 snomed_codes = list(snomed_lookup.keys())\n 292\n 293 # Build placeholders for SNOMED codes\n 294 placeholders = \", \".join([\"%s\"] * len(snomed_codes))\n 295\n 296 # Query to find most recent matching SNOMED code in GP records\n 297 query = f'''\n 298 SELECT\n 299 \"SNOMEDCode\",\n 300 \"EventDateTime\"\n 301 FROM DATA_HUB.PHM.\"PrimaryCareClinicalCoding\"\n 302 WHERE \"PatientPseudonym\" = %s\n 303 AND \"SNOMEDCode\" IN ({placeholders})\n 304 '''\n 305\n 306 params: list = [patient_pseudonym] + snomed_codes\n 307\n 308 if before_date:\n 309 query += ' AND \"EventDateTime\" < %s'\n 310 params.append(before_date.isoformat())\n 311\n 312 query += ' ORDER BY \"EventDateTime\" DESC LIMIT 1'\n 313\n 314 try:\n 315 results = connector.execute_dict(query, tuple(params))\n 316\n 317 if results:\n 318 row = results[0]\n 319 matched_code = row.get(\"SNOMEDCode\")\n 320 event_dt = row.get(\"EventDateTime\")\n 321\n 322 if matched_code and matched_code in snomed_lookup:\n 323 search_term, primary_dir, snomed_desc = snomed_lookup[matched_code]\n 324\n 325 return DirectSnomedMatchResult(\n 326 patient_pseudonym=patient_pseudonym,\n 327 matched=True,\n 328 snomed_code=matched_code,\n 329 snomed_description=snomed_desc,\n 330 search_term=search_term,\n 331 primary_directorate=primary_dir,\n 332 event_date=event_dt,\n 333 source=\"DIRECT_SNOMED\",\n 334 )\n 335\n 336 return result\n 337\n 338 except Exception as e:\n 339 logger.error(f\"Error checking direct SNOMED for patient '{patient_pseudonym}': {e}\")\n 340 return result\n 341\n 342\n 343def get_directorate_from_diagnosis(\n 344 upid: str,\n 345 drug_name: str,\n 346 connector: Optional[SnowflakeConnector] = None,\n 347 db_manager: Optional[DatabaseManager] = None,\n 348 before_date: Optional[date] = None,\n 349) -> DirectorateAssignment:\n 350 \"\"\"\n 351 Get directorate assignment for a patient-drug combination using diagnosis-based lookup.\n 352\n 353 This function attempts to assign a directorate based on the patient's GP records\n 354 (direct SNOMED code matching). If no match is found, it returns a FALLBACK result\n 355 indicating that the caller should use alternative assignment methods (e.g.,\n 356 department_identification() from tools/data.py).\n 357\n 358 Workflow:\n 359 1. Get all SNOMED codes for the drug from ref_drug_snomed_mapping\n 360 2. Query patient's GP records for matching SNOMED codes\n 361 3. If match found  return diagnosis-based directorate and search_term\n 362 4. If no match  return FALLBACK result (caller handles fallback logic)\n 363\n 364 Args:\n 365 upid: Patient's unique patient ID (Provider Code[:3] + PersonKey)\n 366 drug_name: Drug name to look up\n 367 connector: Optional SnowflakeConnector (defaults to singleton)\n 368 db_manager: Optional DatabaseManager (defaults to default_db_manager)\n 369 before_date: Optional date - only check diagnoses before this date\n 370\n 371 Returns:\n 372 DirectorateAssignment with directorate, search_term, and source\n 373 \"\"\"\n 374 result = DirectorateAssignment(\n 375 upid=upid,\n 376 drug_name=drug_name,\n 377 directorate=None,\n 378 source=\"FALLBACK\",\n 379 )\n 380\n 381 # Step 1: Get SNOMED codes for the drug\n 382 drug_snomed_mappings = get_drug_snomed_codes(drug_name, db_manager)\n 383\n 384 if not drug_snomed_mappings:\n 385 logger.debug(f\"No SNOMED mappings found for drug '{drug_name}' - using fallback\")\n 386 return result\n 387\n 388 # Step 2: Check Snowflake availability\n 389 if not SNOWFLAKE_AVAILABLE:\n 390 logger.debug(\"Snowflake not available - using fallback\")\n 391 return result\n 392\n 393 if not is_snowflake_configured():\n 394 logger.debug(\"Snowflake not configured - using fallback\")\n 395 return result\n 396\n 397 # Step 3: Get patient pseudonym from UPID\n 398 # UPID format is Provider Code (3 chars) + PersonKey\n 399 # We need to query Snowflake to get the PatientPseudonym for this PersonKey\n 400 # However, patient_has_indication_direct expects PatientPseudonym, not UPID\n 401 # For now, we'll use UPID as the identifier - the actual integration\n 402 # will need to happen at the DataFrame level where we have PersonKey\n 403 #\n 404 # NOTE: This function will be called from the pipeline where we have\n 405 # access to PatientPseudonym. The UPID is passed for logging/tracking.\n 406\n 407 # Actually, looking at the pipeline, we need PatientPseudonym, not UPID.\n 408 # The caller should pass the PatientPseudonym or we need to look it up.\n 409 # For now, let's assume the caller will use this in a batch context\n 410 # where they can map UPID -> PatientPseudonym.\n 411\n 412 # Let me reconsider: the function signature takes UPID but we need\n 413 # PatientPseudonym for Snowflake. In the pipeline context (fetch_and_transform_data),\n 414 # we'll have the PersonKey column which IS the PatientPseudonym.\n 415 # So UPID = ProviderCode[:3] + PersonKey, and PersonKey = PatientPseudonym.\n 416 #\n 417 # We can extract PatientPseudonym from UPID by removing the first 3 chars.\n 418 patient_pseudonym = upid[3:] if len(upid) > 3 else upid\n 419\n 420 # Step 4: Check patient's GP records for matching SNOMED codes\n 421 match_result = patient_has_indication_direct(\n 422 patient_pseudonym=patient_pseudonym,\n 423 drug_snomed_mappings=drug_snomed_mappings,\n 424 connector=connector,\n 425 before_date=before_date,\n 426 )\n 427\n 428 if match_result.matched and match_result.primary_directorate:\n 429 return DirectorateAssignment(\n 430 upid=upid,\n 431 drug_name=drug_name,\n 432 directorate=match_result.primary_directorate,\n 433 search_term=match_result.search_term,\n 434 source=\"DIAGNOSIS\",\n 435 snomed_code=match_result.snomed_code,\n 436 event_date=match_result.event_date,\n 437 )\n 438\n 439 # No match found - return fallback result\n 440 return result\n 441\n 442\n 443def get_cluster_snomed_codes(\n 444 cluster_id: str,\n 445 connector: Optional[SnowflakeConnector] = None,\n 446 use_cache: bool = True,\n 447) -> ClusterSnomedCodes:\n 448 \"\"\"\n 449 Get all SNOMED codes for a cluster from Snowflake.\n 450\n 451 Queries the ClinicalCodingClusterSnomedCodes table to get all SNOMED codes\n 452 that belong to the specified cluster.\n 453\n 454 Args:\n 455 cluster_id: Cluster ID to look up (e.g., 'RARTH_COD', 'PSORIASIS_COD')\n 456 connector: Optional SnowflakeConnector (defaults to singleton)\n 457 use_cache: Whether to use cached results (default True)\n 458\n 459 Returns:\n 460 ClusterSnomedCodes with list of SNOMED codes and descriptions\n 461 \"\"\"\n 462 if not SNOWFLAKE_AVAILABLE:\n 463 logger.warning(\"Snowflake connector not available\")\n 464 return ClusterSnomedCodes(cluster_id=cluster_id, cluster_description=\"\")\n 465\n 466 if not is_snowflake_configured():\n 467 logger.warning(\"Snowflake not configured - cannot get cluster codes\")\n 468 return ClusterSnomedCodes(cluster_id=cluster_id, cluster_description=\"\")\n 469\n 470 # Check cache first\n 471 cache_key = f\"cluster_snomed_{cluster_id}\"\n 472 if use_cache and is_cache_enabled():\n 473 cache = get_cache()\n 474 cached = cache.get(cache_key)\n 475 if cached is not None and len(cached) > 0:\n 476 logger.debug(f\"Using cached SNOMED codes for cluster '{cluster_id}'\")\n 477 cached_dict = cached[0] # First element is our data dict\n 478 return ClusterSnomedCodes(\n 479 cluster_id=cluster_id,\n 480 cluster_description=str(cached_dict.get(\"description\", \"\")),\n 481 snomed_codes=list(cached_dict.get(\"codes\", [])),\n 482 snomed_descriptions=dict(cached_dict.get(\"descriptions\", {})),\n 483 )\n 484\n 485 if connector is None:\n 486 connector = get_connector()\n 487\n 488 query = '''\n 489 SELECT DISTINCT\n 490 \"Cluster_ID\",\n 491 \"Cluster_Description\",\n 492 \"SNOMEDCode\",\n 493 \"SNOMEDDescription\"\n 494 FROM DATA_HUB.PHM.\"ClinicalCodingClusterSnomedCodes\"\n 495 WHERE \"Cluster_ID\" = %s\n 496 ORDER BY \"SNOMEDCode\"\n 497 '''\n 498\n 499 try:\n 500 results = connector.execute_dict(query, (cluster_id,))\n 501\n 502 if not results:\n 503 logger.warning(f\"No SNOMED codes found for cluster '{cluster_id}'\")\n 504 return ClusterSnomedCodes(cluster_id=cluster_id, cluster_description=\"\")\n 505\n 506 codes = []\n 507 descriptions = {}\n 508 description = results[0].get(\"Cluster_Description\", \"\") if results else \"\"\n 509\n 510 for row in results:\n 511 code = row.get(\"SNOMEDCode\")\n 512 if code:\n 513 codes.append(code)\n 514 descriptions[code] = row.get(\"SNOMEDDescription\", \"\")\n 515\n 516 logger.info(f\"Found {len(codes)} SNOMED codes for cluster '{cluster_id}'\")\n 517\n 518 # Cache the results (using query-based cache with fake params)\n 519 if use_cache and is_cache_enabled():\n 520 cache = get_cache()\n 521 cache_data = [{\n 522 \"description\": description,\n 523 \"codes\": codes,\n 524 \"descriptions\": descriptions,\n 525 }]\n 526 cache.set(cache_key, None, cache_data) # type: ignore[arg-type]\n 527\n 528 return ClusterSnomedCodes(\n 529 cluster_id=cluster_id,\n 530 cluster_description=description,\n 531 snomed_codes=codes,\n 532 snomed_descriptions=descriptions,\n 533 )\n 534\n 535 except Exception as e:\n 536 logger.error(f\"Error getting SNOMED codes for cluster '{cluster_id}': {e}\")\n 537 return ClusterSnomedCodes(cluster_id=cluster_id, cluster_description=\"\")\n 538\n 539\n 540def patient_has_indication(\n 541 patient_pseudonym: str,\n 542 cluster_ids: list[str],\n 543 connector: Optional[SnowflakeConnector] = None,\n 544 before_date: Optional[date] = None,\n 545) -> tuple[bool, Optional[str], Optional[str], Optional[str]]:\n 546 \"\"\"\n 547 Check if a patient has any SNOMED codes from the specified clusters in GP records.\n 548\n 549 Args:\n 550 patient_pseudonym: Patient's pseudonymised NHS number\n 551 cluster_ids: List of cluster IDs to check against\n 552 connector: Optional SnowflakeConnector\n 553 before_date: Optional date - only check diagnoses before this date\n 554\n 555 Returns:\n 556 Tuple of (has_indication, matched_cluster_id, matched_snomed_code, matched_description)\n 557 \"\"\"\n 558 if not SNOWFLAKE_AVAILABLE or not is_snowflake_configured():\n 559 return False, None, None, None\n 560\n 561 if not cluster_ids:\n 562 return False, None, None, None\n 563\n 564 if connector is None:\n 565 connector = get_connector()\n 566\n 567 # Build placeholders for cluster IDs\n 568 placeholders = \", \".join([\"%s\"] * len(cluster_ids))\n 569\n 570 # Query to check if patient has any matching SNOMED code\n 571 query = f'''\n 572 SELECT\n 573 pc.\"SNOMEDCode\",\n 574 cc.\"Cluster_ID\",\n 575 cc.\"SNOMEDDescription\"\n 576 FROM DATA_HUB.PHM.\"PrimaryCareClinicalCoding\" pc\n 577 INNER JOIN DATA_HUB.PHM.\"ClinicalCodingClusterSnomedCodes\" cc\n 578 ON pc.\"SNOMEDCode\" = cc.\"SNOMEDCode\"\n 579 WHERE pc.\"PatientPseudonym\" = %s\n 580 AND cc.\"Cluster_ID\" IN ({placeholders})\n 581 '''\n 582\n 583 params = [patient_pseudonym] + cluster_ids\n 584\n 585 if before_date:\n 586 query += ' AND pc.\"EventDateTime\" < %s'\n 587 params.append(before_date.isoformat())\n 588\n 589 query += ' LIMIT 1'\n 590\n 591 try:\n 592 results = connector.execute_dict(query, tuple(params))\n 593\n 594 if results:\n 595 row = results[0]\n 596 return (\n 597 True,\n 598 row.get(\"Cluster_ID\"),\n 599 row.get(\"SNOMEDCode\"),\n 600 row.get(\"SNOMEDDescription\"),\n 601 )\n 602\n 603 return False, None, None, None\n 604\n 605 except Exception as e:\n 606 logger.error(f\"Error checking indication for patient '{patient_pseudonym}': {e}\")\n 607 return False, None, None, None\n 608\n 609\n 610def validate_indication(\n 611 patient_pseudonym: str,\n 612 drug_name: str,\n 613 connector: Optional[SnowflakeConnector] = None,\n 614 db_manager: Optional[DatabaseManager] = None,\n 615 before_date: Optional[date] = None,\n 616) -> IndicationValidationResult:\n 617 \"\"\"\n 618 Validate that a patient has an appropriate indication for a drug.\n 619\n 620 Full validation workflow:\n 621 1. Get drug's valid indication clusters from local mapping\n 622 2. Check if patient has any matching SNOMED codes in GP records\n 623 3. Return detailed validation result\n 624\n 625 Args:\n 626 patient_pseudonym: Patient's pseudonymised NHS number\n 627 drug_name: Drug name to validate indication for\n 628 connector: Optional SnowflakeConnector\n 629 db_manager: Optional DatabaseManager\n 630 before_date: Optional date - only check diagnoses before this date\n 631\n 632 Returns:\n 633 IndicationValidationResult with validation details\n 634 \"\"\"\n 635 result = IndicationValidationResult(\n 636 patient_pseudonym=patient_pseudonym,\n 637 drug_name=drug_name,\n 638 has_valid_indication=False,\n 639 )\n 640\n 641 # Step 1: Get drug's cluster mappings\n 642 cluster_ids = get_drug_cluster_ids(drug_name, db_manager)\n 643\n 644 if not cluster_ids:\n 645 result.error_message = f\"No cluster mappings found for drug '{drug_name}'\"\n 646 result.source = \"NONE\"\n 647 return result\n 648\n 649 result.checked_clusters = cluster_ids\n 650\n 651 # Step 2: Check Snowflake availability\n 652 if not SNOWFLAKE_AVAILABLE:\n 653 result.error_message = \"Snowflake connector not installed\"\n 654 result.source = \"NONE\"\n 655 return result\n 656\n 657 if not is_snowflake_configured():\n 658 result.error_message = \"Snowflake not configured\"\n 659 result.source = \"NONE\"\n 660 return result\n 661\n 662 # Step 3: Check patient GP records\n 663 has_indication, matched_cluster, matched_code, matched_desc = patient_has_indication(\n 664 patient_pseudonym=patient_pseudonym,\n 665 cluster_ids=cluster_ids,\n 666 connector=connector,\n 667 before_date=before_date,\n 668 )\n 669\n 670 result.has_valid_indication = has_indication\n 671 result.matched_cluster_id = matched_cluster\n 672 result.matched_snomed_code = matched_code\n 673 result.matched_snomed_description = matched_desc\n 674 result.source = \"GP_SNOMED\" if has_indication else \"NONE\"\n 675\n 676 return result\n 677\n 678\n 679def get_indication_match_rate(\n 680 drug_name: str,\n 681 patient_pseudonyms: list[str],\n 682 connector: Optional[SnowflakeConnector] = None,\n 683 db_manager: Optional[DatabaseManager] = None,\n 684 sample_unmatched_count: int = 10,\n 685) -> DrugIndicationMatchRate:\n 686 \"\"\"\n 687 Calculate indication match rate for a drug across a list of patients.\n 688\n 689 Args:\n 690 drug_name: Drug name to check\n 691 patient_pseudonyms: List of patient pseudonymised NHS numbers\n 692 connector: Optional SnowflakeConnector\n 693 db_manager: Optional DatabaseManager\n 694 sample_unmatched_count: Number of unmatched patient IDs to include in sample\n 695\n 696 Returns:\n 697 DrugIndicationMatchRate with match statistics\n 698 \"\"\"\n 699 if connector is None and SNOWFLAKE_AVAILABLE and is_snowflake_configured():\n 700 connector = get_connector()\n 701\n 702 cluster_ids = get_drug_cluster_ids(drug_name, db_manager)\n 703\n 704 total = len(patient_pseudonyms)\n 705 matched = 0\n 706 unmatched = 0\n 707 sample_unmatched: list[str] = []\n 708\n 709 if not cluster_ids:\n 710 logger.warning(f\"No cluster mappings for drug '{drug_name}' - all patients will be unmatched\")\n 711 return DrugIndicationMatchRate(\n 712 drug_name=drug_name,\n 713 total_patients=total,\n 714 patients_with_indication=0,\n 715 patients_without_indication=total,\n 716 match_rate=0.0,\n 717 clusters_checked=[],\n 718 sample_unmatched=patient_pseudonyms[:sample_unmatched_count],\n 719 )\n 720\n 721 for i, pseudonym in enumerate(patient_pseudonyms):\n 722 if i > 0 and i % 100 == 0:\n 723 logger.info(f\"Validating indications: {i}/{total} ({100*i/total:.1f}%)\")\n 724\n 725 has_indication, _, _, _ = patient_has_indication(\n 726 patient_pseudonym=pseudonym,\n 727 cluster_ids=cluster_ids,\n 728 connector=connector,\n 729 )\n 730\n 731 if has_indication:\n 732 matched += 1\n 733 else:\n 734 unmatched += 1\n 735 if len(sample_unmatched) < sample_unmatched_count:\n 736 sample_unmatched.append(pseudonym)\n 737\n 738 match_rate = matched / total if total > 0 else 0.0\n 739\n 740 logger.info(f\"Indication match rate for '{drug_name}': {100*match_rate:.1f}% ({matched}/{total})\")\n 741\n 742 return DrugIndicationMatchRate(\n 743 drug_name=drug_name,\n 744 total_patients=total,\n 745 patients_with_indication=matched,\n 746 patients_without_indication=unmatched,\n 747 match_rate=match_rate,\n 748 clusters_checked=cluster_ids,\n 749 sample_unmatched=sample_unmatched,\n 750 )\n 751\n 752\n 753def batch_validate_indications(\n 754 patient_drug_pairs: list[tuple[str, str]],\n 755 connector: Optional[SnowflakeConnector] = None,\n 756 db_manager: Optional[DatabaseManager] = None,\n 757 progress_callback: Optional[Callable[[int, int], None]] = None,\n 758) -> list[IndicationValidationResult]:\n 759 \"\"\"\n 760 Validate indications for multiple patient-drug pairs efficiently.\n 761\n 762 Args:\n 763 patient_drug_pairs: List of (patient_pseudonym, drug_name) tuples\n 764 connector: Optional SnowflakeConnector\n 765 db_manager: Optional DatabaseManager\n 766 progress_callback: Optional callback(current, total) for progress updates\n 767\n 768 Returns:\n 769 List of IndicationValidationResult for each pair\n 770 \"\"\"\n 771 results = []\n 772 total = len(patient_drug_pairs)\n 773\n 774 # Cache cluster lookups by drug\n 775 drug_clusters_cache = {}\n 776\n 777 for i, (pseudonym, drug_name) in enumerate(patient_drug_pairs):\n 778 if progress_callback:\n 779 progress_callback(i + 1, total)\n 780\n 781 # Get clusters from cache or lookup\n 782 drug_upper = drug_name.upper()\n 783 if drug_upper not in drug_clusters_cache:\n 784 drug_clusters_cache[drug_upper] = get_drug_cluster_ids(drug_name, db_manager)\n 785\n 786 cluster_ids = drug_clusters_cache[drug_upper]\n 787\n 788 if not cluster_ids:\n 789 results.append(IndicationValidationResult(\n 790 patient_pseudonym=pseudonym,\n 791 drug_name=drug_name,\n 792 has_valid_indication=False,\n 793 source=\"NONE\",\n 794 error_message=f\"No cluster mappings for drug '{drug_name}'\",\n 795 ))\n 796 continue\n 797\n 798 # Check patient indication\n 799 has_indication, matched_cluster, matched_code, matched_desc = patient_has_indication(\n 800 patient_pseudonym=pseudonym,\n 801 cluster_ids=cluster_ids,\n 802 connector=connector,\n 803 )\n 804\n 805 results.append(IndicationValidationResult(\n 806 patient_pseudonym=pseudonym,\n 807 drug_name=drug_name,\n 808 has_valid_indication=has_indication,\n 809 matched_cluster_id=matched_cluster,\n 810 matched_snomed_code=matched_code,\n 811 matched_snomed_description=matched_desc,\n 812 checked_clusters=cluster_ids,\n 813 source=\"GP_SNOMED\" if has_indication else \"NONE\",\n 814 ))\n 815\n 816 matched_count = sum(1 for r in results if r.has_valid_indication)\n 817 logger.info(f\"Batch validation complete: {matched_count}/{total} ({100*matched_count/total:.1f}%) with valid indications\")\n 818\n 819 return results\n 820\n 821\n 822def get_available_clusters(\n 823 connector: Optional[SnowflakeConnector] = None,\n 824) -> list[dict]:\n 825 \"\"\"\n 826 Get list of all available SNOMED clusters from Snowflake.\n 827\n 828 Returns:\n 829 List of dicts with cluster_id, cluster_description, code_count\n 830 \"\"\"\n 831 if not SNOWFLAKE_AVAILABLE or not is_snowflake_configured():\n 832 logger.warning(\"Snowflake not available - cannot list clusters\")\n 833 return []\n 834\n 835 if connector is None:\n 836 connector = get_connector()\n 837\n 838 query = '''\n 839 SELECT\n 840 \"Cluster_ID\",\n 841 \"Cluster_Description\",\n 842 COUNT(DISTINCT \"SNOMEDCode\") as code_count\n 843 FROM DATA_HUB.PHM.\"ClinicalCodingClusterSnomedCodes\"\n 844 GROUP BY \"Cluster_ID\", \"Cluster_Description\"\n 845 ORDER BY \"Cluster_ID\"\n 846 '''\n 847\n 848 try:\n 849 results = connector.execute_dict(query)\n 850\n 851 clusters = []\n 852 for row in results:\n 853 clusters.append({\n 854 \"cluster_id\": row.get(\"Cluster_ID\"),\n 855 \"cluster_description\": row.get(\"Cluster_Description\"),\n 856 \"code_count\": row.get(\"code_count\", 0),\n 857 })\n 858\n 859 logger.info(f\"Found {len(clusters)} available SNOMED clusters\")\n 860 return clusters\n 861\n 862 except Exception as e:\n 863 logger.error(f\"Error getting available clusters: {e}\")\n 864 return []\n 865\n 866\n 867def batch_lookup_indication_groups(\n 868 df: \"pd.DataFrame\",\n 869 connector: Optional[SnowflakeConnector] = None,\n 870 db_manager: Optional[DatabaseManager] = None,\n 871 batch_size: int = 500,\n 872) -> \"pd.DataFrame\":\n 873 \"\"\"\n 874 Batch lookup GP diagnosis-based indication groups for a DataFrame of patients.\n 875\n 876 This is the efficient batch version of get_directorate_from_diagnosis().\n 877 Instead of querying Snowflake per patient, it batches the lookups for performance.\n 878\n 879 Strategy:\n 880 1. Get all unique (PersonKey, Drug Name) pairs from DataFrame\n 881 2. For each unique drug, get all SNOMED codes from local SQLite\n 882 3. Build batched Snowflake queries to check GP records\n 883 4. Return indication_df mapping UPID  Indication_Group\n 884\n 885 For unmatched patients, Indication_Group will be their Directory (with suffix).\n 886\n 887 Args:\n 888 df: DataFrame with columns: UPID, Drug Name, Directory, PersonKey\n 889 connector: Optional SnowflakeConnector (defaults to singleton)\n 890 db_manager: Optional DatabaseManager (defaults to default_db_manager)\n 891 batch_size: Number of patients per Snowflake query batch\n 892\n 893 Returns:\n 894 DataFrame with columns: UPID, Indication_Group, Source\n 895 - Indication_Group: Search_Term (if matched) or \"Directory (no GP dx)\" (if not)\n 896 - Source: \"DIAGNOSIS\" or \"FALLBACK\"\n 897 \"\"\"\n 898 import pandas as pd\n 899\n 900 if db_manager is None:\n 901 db_manager = default_db_manager\n 902\n 903 logger.info(f\"Starting batch indication lookup for {len(df)} records...\")\n 904\n 905 # Step 1: Get unique (UPID, Drug Name, PseudoNHSNoLinked, Directory) combinations\n 906 # We need PseudoNHSNoLinked to query Snowflake - this matches PatientPseudonym in GP records\n 907 # Note: PersonKey is LocalPatientID which is provider-specific and does NOT match GP records\n 908 if 'PseudoNHSNoLinked' not in df.columns:\n 909 logger.error(\"DataFrame missing 'PseudoNHSNoLinked' column - cannot lookup GP records\")\n 910 # Return fallback for all patients\n 911 result_df = df[['UPID', 'Directory']].drop_duplicates().copy()\n 912 result_df['Indication_Group'] = result_df['Directory'] + \" (no GP dx)\"\n 913 result_df['Source'] = \"FALLBACK\"\n 914 return result_df[['UPID', 'Indication_Group', 'Source']]\n 915\n 916 # Get unique patient-drug combinations (we need one lookup per patient-drug pair)\n 917 unique_pairs = df[['UPID', 'Drug Name', 'PseudoNHSNoLinked', 'Directory']].drop_duplicates()\n 918 logger.info(f\"Found {len(unique_pairs)} unique patient-drug combinations\")\n 919\n 920 # Step 2: Get all unique drugs and their SNOMED codes\n 921 unique_drugs = unique_pairs['Drug Name'].unique()\n 922 logger.info(f\"Building SNOMED lookup for {len(unique_drugs)} unique drugs...\")\n 923\n 924 # Build drug -> list of DrugSnomedMapping dict\n 925 drug_snomed_map: dict[str, list[DrugSnomedMapping]] = {}\n 926 all_snomed_codes: set[str] = set()\n 927 snomed_to_drug_searchterm: dict[str, list[tuple[str, str, str]]] = {} # snomed -> [(drug, search_term, primary_dir), ...]\n 928\n 929 for drug_name in unique_drugs:\n 930 mappings = get_drug_snomed_codes(drug_name, db_manager)\n 931 drug_snomed_map[drug_name] = mappings\n 932\n 933 for m in mappings:\n 934 all_snomed_codes.add(m.snomed_code)\n 935 if m.snomed_code not in snomed_to_drug_searchterm:\n 936 snomed_to_drug_searchterm[m.snomed_code] = []\n 937 snomed_to_drug_searchterm[m.snomed_code].append(\n 938 (drug_name, m.search_term, m.primary_directorate)\n 939 )\n 940\n 941 logger.info(f\"Total SNOMED codes to check: {len(all_snomed_codes)}\")\n 942\n 943 # Step 3: Check Snowflake availability\n 944 if not SNOWFLAKE_AVAILABLE or not is_snowflake_configured():\n 945 logger.warning(\"Snowflake not available - returning fallback for all patients\")\n 946 result_df = unique_pairs[['UPID', 'Directory']].copy()\n 947 result_df['Indication_Group'] = result_df['Directory'] + \" (no GP dx)\"\n 948 result_df['Source'] = \"FALLBACK\"\n 949 return result_df[['UPID', 'Indication_Group', 'Source']].drop_duplicates(subset=['UPID'])\n 950\n 951 if connector is None:\n 952 connector = get_connector()\n 953\n 954 # Step 4: Query GP records for all patients in batches\n 955 # The query finds the most recent matching SNOMED code for each patient\n 956\n 957 # Get unique PseudoNHSNoLinked values (each = one patient in GP records)\n 958 unique_patients = unique_pairs[['PseudoNHSNoLinked', 'UPID', 'Directory']].drop_duplicates(subset=['PseudoNHSNoLinked'])\n 959 patient_pseudonyms = unique_patients['PseudoNHSNoLinked'].tolist()\n 960\n 961 logger.info(f\"Querying GP records for {len(patient_pseudonyms)} unique patients in batches of {batch_size}...\")\n 962\n 963 # Results dict: PersonKey -> (snomed_code, event_date)\n 964 gp_matches: dict[str, tuple[str, Any]] = {}\n 965\n 966 # Convert SNOMED codes to list for query\n 967 snomed_list = list(all_snomed_codes)\n 968\n 969 if not snomed_list:\n 970 logger.warning(\"No SNOMED codes to check - returning fallback for all patients\")\n 971 result_df = unique_pairs[['UPID', 'Directory']].copy()\n 972 result_df['Indication_Group'] = result_df['Directory'] + \" (no GP dx)\"\n 973 result_df['Source'] = \"FALLBACK\"\n 974 return result_df[['UPID', 'Indication_Group', 'Source']].drop_duplicates(subset=['UPID'])\n 975\n 976 # Build SNOMED IN clause (reused across batches)\n 977 snomed_placeholders = \", \".join([\"%s\"] * len(snomed_list))\n 978\n 979 # Process patients in batches\n 980 for batch_start in range(0, len(patient_pseudonyms), batch_size):\n 981 batch_end = min(batch_start + batch_size, len(patient_pseudonyms))\n 982 batch_pseudonyms = patient_pseudonyms[batch_start:batch_end]\n 983\n 984 logger.info(f\"Batch {batch_start//batch_size + 1}: patients {batch_start} to {batch_end}\")\n 985\n 986 # Build patient IN clause\n 987 patient_placeholders = \", \".join([\"%s\"] * len(batch_pseudonyms))\n 988\n 989 # Query to find all matching SNOMED codes for these patients\n 990 # We'll get all matches and pick the most recent per patient in Python\n 991 query = f'''\n 992 SELECT\n 993 \"PatientPseudonym\",\n 994 \"SNOMEDCode\",\n 995 \"EventDateTime\"\n 996 FROM DATA_HUB.PHM.\"PrimaryCareClinicalCoding\"\n 997 WHERE \"PatientPseudonym\" IN ({patient_placeholders})\n 998 AND \"SNOMEDCode\" IN ({snomed_placeholders})\n 999 ORDER BY \"PatientPseudonym\", \"EventDateTime\" DESC\n 1000 '''\n 1001\n 1002 params = tuple(batch_pseudonyms) + tuple(snomed_list)\n 1003\n 1004 try:\n 1005 results = connector.execute_dict(query, params)\n 1006\n 1007 # Process results - pick most recent per patient\n 1008 for row in results:\n 1009 person_key = row.get(\"PatientPseudonym\")\n 1010 snomed_code = row.get(\"SNOMEDCode\")\n 1011 event_date = row.get(\"EventDateTime\")\n 1012\n 1013 if person_key and snomed_code:\n 1014 # Keep only if we haven't seen this patient yet (first = most recent due to ORDER BY)\n 1015 if person_key not in gp_matches:\n 1016 gp_matches[person_key] = (snomed_code, event_date)\n 1017\n 1018 except Exception as e:\n 1019 logger.error(f\"Error querying GP records for batch: {e}\")\n 1020 # Continue with other batches\n 1021\n 1022 logger.info(f\"Found GP matches for {len(gp_matches)} patients\")\n 1023\n 1024 # Step 5: Build result DataFrame\n 1025 # For each unique_pair, determine Indication_Group based on match status\n 1026 results_list = []\n 1027\n 1028 # We need to dedupe by UPID - a patient might be on multiple drugs\n 1029 # Strategy: For each UPID, use the most recent match (if any)\n 1030 upid_to_match: dict[str, tuple[str, str]] = {} # UPID -> (Indication_Group, Source)\n 1031\n 1032 for _, row in unique_pairs.iterrows():\n 1033 upid = row['UPID']\n 1034 drug_name = row['Drug Name']\n 1035 patient_pseudonym = row['PseudoNHSNoLinked']\n 1036 directory = row['Directory']\n 1037\n 1038 # Check if patient has GP match (using PseudoNHSNoLinked which matches PatientPseudonym in GP)\n 1039 if patient_pseudonym in gp_matches:\n 1040 matched_snomed, event_date = gp_matches[patient_pseudonym]\n 1041\n 1042 # Find the search_term for this SNOMED code and drug\n 1043 # (A SNOMED code might map to multiple drugs with different search_terms)\n 1044 if matched_snomed in snomed_to_drug_searchterm:\n 1045 # Look for match with current drug first\n 1046 search_term = None\n 1047 for drug, st, pd in snomed_to_drug_searchterm[matched_snomed]:\n 1048 if drug.upper() == drug_name.upper():\n 1049 search_term = st\n 1050 break\n 1051 # If no drug-specific match, use any match\n 1052 if search_term is None:\n 1053 search_term = snomed_to_drug_searchterm[matched_snomed][0][1]\n 1054\n 1055 # Only update if we don't have a match for this UPID yet\n 1056 if upid not in upid_to_match:\n 1057 upid_to_match[upid] = (search_term, \"DIAGNOSIS\")\n 1058 else:\n 1059 # Shouldn't happen but fallback just in case\n 1060 if upid not in upid_to_match:\n 1061 upid_to_match[upid] = (directory + \" (no GP dx)\", \"FALLBACK\")\n 1062 else:\n 1063 # No GP match - use fallback\n 1064 if upid not in upid_to_match:\n 1065 upid_to_match[upid] = (directory + \" (no GP dx)\", \"FALLBACK\")\n 1066\n 1067 # Build result DataFrame\n 1068 for upid, (indication_group, source) in upid_to_match.items():\n 1069 results_list.append({\n 1070 'UPID': upid,\n 1071 'Indication_Group': indication_group,\n 1072 'Source': source,\n 1073 })\n 1074\n 1075 result_df = pd.DataFrame(results_list)\n 1076\n 1077 # Log statistics\n 1078 diagnosis_count = len([s for s in result_df['Source'] if s == \"DIAGNOSIS\"])\n 1079 fallback_count = len([s for s in result_df['Source'] if s == \"FALLBACK\"])\n 1080 total = len(result_df)\n 1081\n 1082 logger.info(f\"Indication lookup complete:\")\n 1083 logger.info(f\" Total unique patients: {total}\")\n 1084 logger.info(f\" DIAGNOSIS matches: {diagnosis_count} ({100*diagnosis_count/total:.1f}%)\")\n 1085 logger.info(f\" FALLBACK (no GP match): {fallback_count} ({100*fallback_count/total:.1f}%)\")\n 1086\n 1087 return result_df\n 1088\n 1089\n 1090# === Drug-to-indication mapping from DimSearchTerm.csv ===\n 1091\n 1092\n 1093# Merge related Search_Terms into canonical names.\n 1094# Asthma variants are clinically the same condition at different severity levels.\n 1095# Urticaria is a separate condition  do NOT merge with asthma.\n 1096SEARCH_TERM_MERGE_MAP: dict[str, str] = {\n 1097 \"allergic asthma\": \"asthma\",\n 1098 \"severe persistent allergic asthma\": \"asthma\",\n 1099}\n 1100\n 1101\n 1102def load_drug_indication_mapping(\n 1103 csv_path: Optional[str] = None,\n 1104) -> tuple[dict[str, list[str]], dict[str, list[str]]]:\n 1105 \"\"\"\n 1106 Load the drug-to-Search_Term mapping from DimSearchTerm.csv.\n 1107\n 1108 Builds two lookup dicts:\n 1109 - fragment_to_search_terms: drug fragment (UPPERCASE) -> list of Search_Terms containing it\n 1110 - search_term_to_fragments: search_term -> list of drug fragments (UPPERCASE)\n 1111\n 1112 DimSearchTerm.csv has columns: Search_Term, CleanedDrugName, PrimaryDirectorate\n 1113 CleanedDrugName is pipe-separated (e.g., \"ADALIMUMAB|GOLIMUMAB|IXEKIZUMAB\").\n 1114\n 1115 Note: A Search_Term can appear multiple times with different PrimaryDirectorates\n 1116 (e.g., \"diabetes\" appears under both DIABETIC MEDICINE and OPHTHALMOLOGY).\n 1117 Drug fragments from all rows for the same Search_Term are combined.\n 1118\n 1119 Asthma-related Search_Terms (\"allergic asthma\", \"severe persistent allergic asthma\")\n 1120 are merged into \"asthma\" to match the CLUSTER_MAPPING_SQL normalization.\n 1121 \"urticaria\" stays separate.\n 1122\n 1123 Args:\n 1124 csv_path: Path to DimSearchTerm.csv. Defaults to data/DimSearchTerm.csv.\n 1125\n 1126 Returns:\n 1127 Tuple of (fragment_to_search_terms, search_term_to_fragments)\n 1128 \"\"\"\n 1129 if csv_path is None:\n 1130 csv_path = str(Path(__file__).parent.parent / \"data\" / \"DimSearchTerm.csv\")\n 1131\n 1132 fragment_to_search_terms: dict[str, list[str]] = {}\n 1133 search_term_to_fragments: dict[str, list[str]] = {}\n 1134\n 1135 try:\n 1136 with open(csv_path, \"r\", encoding=\"utf-8\") as f:\n 1137 reader = csv.DictReader(f)\n 1138 for row in reader:\n 1139 search_term = row.get(\"Search_Term\", \"\").strip()\n 1140 drug_names_raw = row.get(\"CleanedDrugName\", \"\").strip()\n 1141\n 1142 # Normalize asthma variants to canonical \"asthma\"\n 1143 search_term = SEARCH_TERM_MERGE_MAP.get(search_term, search_term)\n 1144\n 1145 if not search_term or not drug_names_raw:\n 1146 continue\n 1147\n 1148 fragments = [frag.strip().upper() for frag in drug_names_raw.split(\"|\") if frag.strip()]\n 1149\n 1150 # Build search_term -> fragments (accumulate for duplicate Search_Terms)\n 1151 if search_term not in search_term_to_fragments:\n 1152 search_term_to_fragments[search_term] = []\n 1153 for frag in fragments:\n 1154 if frag not in search_term_to_fragments[search_term]:\n 1155 search_term_to_fragments[search_term].append(frag)\n 1156\n 1157 # Build fragment -> search_terms\n 1158 for frag in fragments:\n 1159 if frag not in fragment_to_search_terms:\n 1160 fragment_to_search_terms[frag] = []\n 1161 if search_term not in fragment_to_search_terms[frag]:\n 1162 fragment_to_search_terms[frag].append(search_term)\n 1163\n 1164 logger.info(\n 1165 f\"Loaded drug-indication mapping: {len(search_term_to_fragments)} Search_Terms, \"\n 1166 f\"{len(fragment_to_search_terms)} drug fragments\"\n 1167 )\n 1168\n 1169 except FileNotFoundError:\n 1170 logger.error(f\"DimSearchTerm.csv not found at {csv_path}\")\n 1171 except Exception as e:\n 1172 logger.error(f\"Error loading DimSearchTerm.csv: {e}\")\n 1173\n 1174 return fragment_to_search_terms, search_term_to_fragments\n 1175\n 1176\n 1177def get_search_terms_for_drug(\n 1178 drug_name: str,\n 1179 search_term_to_fragments: dict[str, list[str]],\n 1180) -> list[str]:\n 1181 \"\"\"\n 1182 Get all Search_Terms that list a given drug using substring matching.\n 1183\n 1184 Checks if any drug fragment from DimSearchTerm is a SUBSTRING of the given\n 1185 drug name (case-insensitive). This handles both exact matches (ADALIMUMAB)\n 1186 and partial fragments (PEGYLATED, INHALED).\n 1187\n 1188 Args:\n 1189 drug_name: HCD drug name (e.g., \"ADALIMUMAB 40MG\", \"PEGYLATED LIPOSOMAL DOXORUBICIN\")\n 1190 search_term_to_fragments: Mapping of search_term -> list of drug fragments\n 1191\n 1192 Returns:\n 1193 List of Search_Terms whose drug fragments match the drug name\n 1194 \"\"\"\n 1195 drug_name_upper = drug_name.upper()\n 1196 matched_terms: list[str] = []\n 1197\n 1198 for search_term, fragments in search_term_to_fragments.items():\n 1199 for frag in fragments:\n 1200 if frag in drug_name_upper:\n 1201 matched_terms.append(search_term)\n 1202 break # One matching fragment is enough for this Search_Term\n 1203\n 1204 return matched_terms\n 1205\n 1206\n 1207# === NEW APPROACH: Query Snowflake directly using cluster CTE ===\n 1208\n 1209# The cluster query mapping (embedded from snomed_indication_mapping_query.sql)\n 1210# This maps Search_Term -> Cluster_ID for ~148 clinical conditions\n 1211CLUSTER_MAPPING_SQL = \"\"\"\n 1212WITH SearchTermClusters AS (\n 1213 SELECT Search_Term, Cluster_ID FROM (VALUES\n 1214 ('acute lymphoblastic leukaemia', 'HAEMCANMORPH_COD'),\n 1215 ('acute myeloid leukaemia', 'C19HAEMCAN_COD'),\n 1216 ('acute promyelocytic leukaemia', 'HAEMCANMORPH_COD'),\n 1217 ('asthma', 'AST_COD'),\n 1218 ('allergic rhinitis', 'MILDINTAST_COD'),\n 1219 ('alzheimer''s disease', 'DEMALZ_COD'),\n 1220 ('amyloidosis', 'AMYLOID_COD'),\n 1221 ('anaemia', 'eFI2_AnaemiaTimeSensitive'),\n 1222 ('anaplastic large cell lymphoma', 'C19HAEMCAN_COD'),\n 1223 ('apixaban', 'DOACCON_COD'),\n 1224 ('aplastic anaemia', 'eFI2_AnaemiaEver'),\n 1225 ('arthritis', 'eFI2_InflammatoryArthritis'),\n 1226 ('asthma', 'eFI2_Asthma'),\n 1227 ('atopic dermatitis', 'ATOPDERM_COD'),\n 1228 ('atrial fibrillation', 'eFI2_AtrialFibrillation'),\n 1229 ('attention deficit hyperactivity disorder', 'ADHD_COD'),\n 1230 ('bipolar disorder', 'MH_COD'),\n 1231 ('bladder', 'eFI2_UrinaryIncontinence'),\n 1232 ('breast cancer', 'BRCANSCR_COD'),\n 1233 ('cardiomyopathy', 'eFI2_HarmfulDrinking'),\n 1234 ('cardiovascular disease', 'CVDRISKASS_COD'),\n 1235 ('cervical cancer', 'CSDEC_COD'),\n 1236 ('cholangiocarcinoma', 'eFI2_Cancer'),\n 1237 ('chronic kidney disease', 'CKD_COD'),\n 1238 ('chronic liver disease', 'eFI2_LiverProblems'),\n 1239 ('chronic lymphocytic leukaemia', 'EPPHAEMCAN_COD'),\n 1240 ('chronic myeloid leukaemia', 'EPPHAEMCAN_COD'),\n 1241 ('chronic obstructive pulmonary disease', 'eFI2_COPD'),\n 1242 ('colon cancer', 'eFI2_Cancer'),\n 1243 ('colorectal cancer', 'GICANREF_COD'),\n 1244 ('constipation', 'CHRONCONSTIP_COD'),\n 1245 ('covid-19', 'POSSPOSTCOVID_COD'),\n 1246 ('crohn''s disease', 'eFI2_InflammatoryBowelDisease'),\n 1247 ('cutaneous t-cell lymphoma', 'C19HAEMCAN_COD'),\n 1248 ('cystic fibrosis', 'CUST_ICB_CYSTIC_FIBROSIS'),\n 1249 ('deep vein thrombosis', 'VTE_COD'),\n 1250 ('depression', 'eFI2_Depression'),\n 1251 ('diabetes', 'eFI2_DiabetesEver'),\n 1252 ('diabetic retinopathy', 'DRSELIGIBILITY_COD'),\n 1253 ('diffuse large b-cell lymphoma', 'C19HAEMCAN_COD'),\n 1254 ('dravet syndrome', 'EPIL_COD'),\n 1255 ('drug misuse', 'ILLSUBINT_COD'),\n 1256 ('dyspepsia', 'eFI2_AbdominalPain'),\n 1257 ('epilepsy', 'eFI2_Seizures'),\n 1258 ('fallopian tube', 'STERIL_COD'),\n 1259 ('follicular lymphoma', 'C19HAEMCAN_COD'),\n 1260 ('gastric cancer', 'eFI2_Cancer'),\n 1261 ('giant cell arteritis', 'GCA_COD'),\n 1262 ('glioma', 'NHAEMCANMORPH_COD'),\n 1263 ('gout', 'eFI2_InflammatoryArthritis'),\n 1264 ('graft versus host disease', 'GVHD_COD'),\n 1265 ('granulomatosis with polyangiitis', 'WEGENERVASC_COD'),\n 1266 ('growth hormone deficiency', 'HYPOPITUITARY_COD'),\n 1267 ('hand eczema', 'ECZEMA_COD'),\n 1268 ('heart failure', 'eFI2_HeartFailure'),\n 1269 ('hepatitis b', 'HEPBCVAC_COD'),\n 1270 ('hepatocellular carcinoma', 'eFI2_Cancer'),\n 1271 ('hiv', 'PREFLANG_COD'),\n 1272 ('hodgkin lymphoma', 'HAEMCANMORPH_COD'),\n 1273 ('hormone receptor', 'eFI2_ThyroidProblems'),\n 1274 ('hypercholesterolaemia', 'CLASSFH_COD'),\n 1275 ('immune thrombocytopenia', 'ITP_COD'),\n 1276 ('influenza', 'FLUINVITE_COD'),\n 1277 ('insomnia', 'eFI2_SleepProblems'),\n 1278 ('irritable bowel syndrome', 'IBS_COD'),\n 1279 ('ischaemic stroke', 'OSTR_COD'),\n 1280 ('juvenile idiopathic arthritis', 'RARTHAD_COD'),\n 1281 ('kidney transplant', 'RENALTRANSP_COD'),\n 1282 ('leukaemia', 'eFI2_Cancer'),\n 1283 ('lung cancer', 'FTCANREF_COD'),\n 1284 ('lymphoma', 'C19HAEMCAN_COD'),\n 1285 ('macular degeneration', 'CUST_ICB_VISUAL_IMPAIRMENT'),\n 1286 ('macular oedema', 'CUST_ICB_VISUAL_IMPAIRMENT'),\n 1287 ('major depressive episodes', 'eFI2_Depression'),\n 1288 ('malignant melanoma', 'eFI2_Cancer'),\n 1289 ('malignant pleural mesothelioma', 'LUNGCAN_COD'),\n 1290 ('manic episode', 'MH_COD'),\n 1291 ('mantle cell lymphoma', 'HAEMCANMORPH_COD'),\n 1292 ('melanoma', 'eFI2_Cancer'),\n 1293 ('merkel cell carcinoma', 'C19CAN_COD'),\n 1294 ('migraine', 'eFI2_Headache'),\n 1295 ('motor neurone disease', 'MND_COD'),\n 1296 ('multiple myeloma', 'C19HAEMCAN_COD'),\n 1297 ('multiple sclerosis', 'MS_COD'),\n 1298 ('myelodysplastic', 'eFI2_AnaemiaEver'),\n 1299 ('myelofibrosis', 'MDS_COD'),\n 1300 ('myocardial infarction', 'eFI2_IschaemicHeartDisease'),\n 1301 ('myotonia', 'CNDATRISK2_COD'),\n 1302 ('narcolepsy', 'LD_COD'),\n 1303 ('neuroendocrine tumour', 'LUNGCAN_COD'),\n 1304 ('non-small cell lung cancer', 'LUNGCAN_COD'),\n 1305 ('non-small-cell lung cancer', 'FTCANREF_COD'),\n 1306 ('obesity', 'BMI30_COD'),\n 1307 ('osteoarthritis', 'CUST_ICB_OSTEOARTHRITIS'),\n 1308 ('osteoporosis', 'eFI2_Osteoporosis'),\n 1309 ('osteosarcoma', 'NHAEMCANMORPH_COD'),\n 1310 ('ovarian cancer', 'C19CAN_COD'),\n 1311 ('peripheral arterial disease', 'PADEXC_COD'),\n 1312 ('plaque psoriasis', 'PSORIASIS_COD'),\n 1313 ('polycystic kidney disease', 'EPPCONGMALF_COD'),\n 1314 ('polycythaemia vera', 'C19HAEMCAN_COD'),\n 1315 ('pregnancy', 'C19PREG_COD'),\n 1316 ('primary biliary cholangitis', 'eFI2_LiverProblems'),\n 1317 ('primary hypercholesterolaemia', 'FNFHYP_COD'),\n 1318 ('prostate cancer', 'EPPSOLIDCAN_COD'),\n 1319 ('psoriasis', 'PSORIASIS_COD'),\n 1320 ('psoriatic arthritis', 'RARTHAD_COD'),\n 1321 ('pulmonary embolism', 'eFI2_RespiratoryDiseaseTimeSensitive'),\n 1322 ('pulmonary fibrosis', 'ILD_COD'),\n 1323 ('relapsing multiple sclerosis', 'MS_COD'),\n 1324 ('renal cell carcinoma', 'C19CAN_COD'),\n 1325 ('renal transplantation', 'RENALTRANSP_COD'),\n 1326 ('retinal vein occlusion', 'CUST_ICB_VISUAL_IMPAIRMENT'),\n 1327 ('rheumatoid arthritis', 'eFI2_InflammatoryArthritis'),\n 1328 ('rivaroxaban', 'DOACCON_COD'),\n 1329 ('schizophrenia', 'MH_COD'),\n 1330 ('seizures', 'LSZFREQ_COD'),\n 1331 ('sepsis', 'C19ACTIVITY_COD'),\n 1332 ('asthma', 'SEVAST_COD'),\n 1333 ('sickle cell disease', 'SICKLE_COD'),\n 1334 ('sleep apnoea', 'CUST_ICB_NON_SEVERE_LDA'),\n 1335 ('smoking cessation', 'SMOKINGINT_COD'),\n 1336 ('soft tissue sarcoma', 'NHAEMCANMORPH_COD'),\n 1337 ('spinal muscular atrophy', 'MND_COD'),\n 1338 ('squamous cell', 'C19CAN_COD'),\n 1339 ('squamous cell carcinoma', 'C19CAN_COD'),\n 1340 ('stem cell transplant', 'ALLOTRANSP_COD'),\n 1341 ('stroke', 'eFI2_Stroke'),\n 1342 ('systemic lupus erythematosus', 'SLUPUS_COD'),\n 1343 ('systemic mastocytosis', 'HAEMCANMORPH_COD'),\n 1344 ('thrombocytopenic purpura', 'TTP_COD'),\n 1345 ('thrombotic thrombocytopenic purpura', 'TTP_COD'),\n 1346 ('thyroid cancer', 'C19CAN_COD'),\n 1347 ('tophaceous gout', 'CUST_ICB_OSTEOARTHRITIS'),\n 1348 ('transitional cell carcinoma', 'C19CAN_COD'),\n 1349 ('type 1 diabetes', 'DMTYPE1_COD'),\n 1350 ('type 2 diabetes', 'DMTYPE2_COD'),\n 1351 ('ulcerative colitis', 'eFI2_InflammatoryBowelDisease'),\n 1352 ('urothelial carcinoma', 'NHAEMCANMORPH_COD'),\n 1353 ('urticaria', 'XSAL_COD'),\n 1354 ('uveitis', 'CUST_ICB_VISUAL_IMPAIRMENT'),\n 1355 ('vascular disease', 'CVDINVITE_COD'),\n 1356 ('vasculitis', 'CRYOGLOBVASC_COD')\n 1357 ) AS t(Search_Term, Cluster_ID)\n 1358),\n 1359\n 1360ClusterCodes AS (\n 1361 SELECT\n 1362 stc.Search_Term,\n 1363 c.\"SNOMEDCode\",\n 1364 c.\"SNOMEDDescription\"\n 1365 FROM SearchTermClusters stc\n 1366 JOIN DATA_HUB.PHM.\"ClinicalCodingClusterSnomedCodes\" c\n 1367 ON stc.Cluster_ID = c.\"Cluster_ID\"\n 1368 WHERE c.\"SNOMEDCode\" IS NOT NULL\n 1369),\n 1370\n 1371ExplicitCodes AS (\n 1372 SELECT Search_Term, SNOMEDCode, SNOMEDDescription FROM (VALUES\n 1373 ('acute coronary syndrome', '837091000000100', 'Manual mapping'),\n 1374 ('ankylosing spondylitis', '162930007', 'Manual mapping'),\n 1375 ('ankylosing spondylitis', '239805001', 'Manual mapping'),\n 1376 ('ankylosing spondylitis', '239810002', 'Manual mapping'),\n 1377 ('ankylosing spondylitis', '239811003', 'Manual mapping'),\n 1378 ('ankylosing spondylitis', '394990003', 'Manual mapping'),\n 1379 ('ankylosing spondylitis', '429712009', 'Manual mapping'),\n 1380 ('ankylosing spondylitis', '441562009', 'Manual mapping'),\n 1381 ('ankylosing spondylitis', '441680005', 'Manual mapping'),\n 1382 ('ankylosing spondylitis', '441930001', 'Manual mapping'),\n 1383 ('axial spondyloarthritis', '723116002', 'Manual mapping'),\n 1384 ('choroidal neovascularisation', '380621000000102', 'Manual mapping'),\n 1385 ('choroidal neovascularisation', '733124000', 'Manual mapping')\n 1386 ) AS t(Search_Term, SNOMEDCode, SNOMEDDescription)\n 1387),\n 1388\n 1389AllIndicationCodes AS (\n 1390 SELECT Search_Term, \"SNOMEDCode\" AS SNOMEDCode, \"SNOMEDDescription\" AS SNOMEDDescription\n 1391 FROM ClusterCodes\n 1392 UNION ALL\n 1393 SELECT Search_Term, SNOMEDCode, SNOMEDDescription\n 1394 FROM ExplicitCodes\n 1395)\n 1396\"\"\"\n 1397\n 1398\n 1399def get_patient_indication_groups(\n 1400 patient_pseudonyms: list[str],\n 1401 connector: Optional[SnowflakeConnector] = None,\n 1402 batch_size: int = 500,\n 1403 earliest_hcd_date: Optional[str] = None,\n 1404) -> \"pd.DataFrame\":\n 1405 \"\"\"\n 1406 Batch lookup GP diagnosis-based indication groups using Snowflake cluster query.\n 1407\n 1408 Returns ALL matching Search_Terms per patient with code_frequency (count of\n 1409 matching SNOMED codes). This enables drug-aware indication matching where\n 1410 each drug is cross-referenced against the patient's GP diagnoses.\n 1411\n 1412 The query:\n 1413 1. Uses the cluster mapping CTE to get all Search_Term -> SNOMED code mappings\n 1414 2. Joins with PrimaryCareClinicalCoding to find patients with matching codes\n 1415 3. Groups by patient + Search_Term and counts matching codes (code_frequency)\n 1416 4. Optionally restricts to GP codes from earliest_hcd_date onwards\n 1417\n 1418 Args:\n 1419 patient_pseudonyms: List of PseudoNHSNoLinked values (matches PatientPseudonym in GP records)\n 1420 connector: Optional SnowflakeConnector (defaults to singleton)\n 1421 batch_size: Number of patients per Snowflake query batch (default 500)\n 1422 earliest_hcd_date: Optional ISO date string (YYYY-MM-DD). If provided, only\n 1423 counts GP codes from this date onwards. Should be MIN(Intervention Date)\n 1424 from the HCD DataFrame to restrict to the HCD data window.\n 1425\n 1426 Returns:\n 1427 DataFrame with columns:\n 1428 - PatientPseudonym: The patient identifier (PseudoNHSNoLinked value)\n 1429 - Search_Term: The matched indication (e.g., \"rheumatoid arthritis\")\n 1430 - code_frequency: Count of matching SNOMED codes for this Search_Term\n 1431\n 1432 Multiple rows per patient (one per matched Search_Term).\n 1433 Patients not found in results have no matching GP diagnosis.\n 1434 \"\"\"\n 1435 import pandas as pd\n 1436\n 1437 logger.info(f\"Starting Snowflake-direct indication lookup for {len(patient_pseudonyms)} patients...\")\n 1438 if earliest_hcd_date:\n 1439 logger.info(f\" Restricting GP codes to >= {earliest_hcd_date}\")\n 1440\n 1441 # Handle edge case: empty patient list\n 1442 if not patient_pseudonyms:\n 1443 logger.warning(\"Empty patient list provided\")\n 1444 return pd.DataFrame(columns=['PatientPseudonym', 'Search_Term', 'code_frequency'])\n 1445\n 1446 # Check Snowflake availability\n 1447 if not SNOWFLAKE_AVAILABLE:\n 1448 logger.error(\"Snowflake connector not available - cannot lookup GP records\")\n 1449 return pd.DataFrame(columns=['PatientPseudonym', 'Search_Term', 'code_frequency'])\n 1450\n 1451 if not is_snowflake_configured():\n 1452 logger.error(\"Snowflake not configured - cannot lookup GP records\")\n 1453 return pd.DataFrame(columns=['PatientPseudonym', 'Search_Term', 'code_frequency'])\n 1454\n 1455 if connector is None:\n 1456 connector = get_connector()\n 1457\n 1458 # Results list to collect all matches\n 1459 all_results: list[dict] = []\n 1460\n 1461 # Process patients in batches\n 1462 total_patients = len(patient_pseudonyms)\n 1463 for batch_start in range(0, total_patients, batch_size):\n 1464 batch_end = min(batch_start + batch_size, total_patients)\n 1465 batch_pseudonyms = patient_pseudonyms[batch_start:batch_end]\n 1466 batch_num = batch_start // batch_size + 1\n 1467 total_batches = (total_patients + batch_size - 1) // batch_size\n 1468\n 1469 logger.info(f\"Batch {batch_num}/{total_batches}: patients {batch_start + 1} to {batch_end}\")\n 1470\n 1471 # Build patient IN clause placeholders\n 1472 patient_placeholders = \", \".join([\"%s\"] * len(batch_pseudonyms))\n 1473\n 1474 # Build WHERE clause with optional date filter\n 1475 date_filter = \"\"\n 1476 if earliest_hcd_date:\n 1477 date_filter = f\"\\n AND pc.\\\"EventDateTime\\\" >= %s\"\n 1478\n 1479 # Build the full query with cluster CTE\n 1480 # Returns ALL matching Search_Terms per patient with code_frequency\n 1481 # code_frequency = COUNT of matching SNOMED codes per Search_Term per patient\n 1482 query = f\"\"\"\n 1483{CLUSTER_MAPPING_SQL}\n 1484SELECT\n 1485 pc.\"PatientPseudonym\" AS \"PatientPseudonym\",\n 1486 aic.Search_Term AS \"Search_Term\",\n 1487 COUNT(*) AS \"code_frequency\"\n 1488FROM DATA_HUB.PHM.\"PrimaryCareClinicalCoding\" pc\n 1489INNER JOIN AllIndicationCodes aic\n 1490 ON pc.\"SNOMEDCode\" = aic.SNOMEDCode\n 1491WHERE pc.\"PatientPseudonym\" IN ({patient_placeholders}){date_filter}\n 1492GROUP BY pc.\"PatientPseudonym\", aic.Search_Term\n 1493\"\"\"\n 1494\n 1495 # Build params: patient pseudonyms + optional date\n 1496 params = list(batch_pseudonyms)\n 1497 if earliest_hcd_date:\n 1498 params.append(earliest_hcd_date)\n 1499\n 1500 try:\n 1501 results = connector.execute_dict(query, tuple(params))\n 1502\n 1503 for row in results:\n 1504 all_results.append({\n 1505 'PatientPseudonym': row.get('PatientPseudonym'),\n 1506 'Search_Term': row.get('Search_Term'),\n 1507 'code_frequency': row.get('code_frequency', 0),\n 1508 })\n 1509\n 1510 logger.debug(f\"Batch {batch_num}: found {len(results)} patient-indication matches\")\n 1511\n 1512 except Exception as e:\n 1513 logger.error(f\"Error querying GP records for batch {batch_num}: {e}\")\n 1514 # Continue with other batches - partial results are better than none\n 1515\n 1516 # Build result DataFrame\n 1517 result_df = pd.DataFrame(all_results)\n 1518\n 1519 # Log summary statistics\n 1520 if len(result_df) > 0:\n 1521 unique_patients = result_df['PatientPseudonym'].nunique()\n 1522 total_rows = len(result_df)\n 1523 match_rate = 100 * unique_patients / total_patients\n 1524 unique_terms = result_df['Search_Term'].nunique()\n 1525 avg_indications = total_rows / unique_patients if unique_patients > 0 else 0\n 1526 logger.info(f\"Indication lookup complete:\")\n 1527 logger.info(f\" Total patients queried: {total_patients}\")\n 1528 logger.info(f\" Patients with GP match: {unique_patients} ({match_rate:.1f}%)\")\n 1529 logger.info(f\" Total patient-indication rows: {total_rows} (avg {avg_indications:.1f} per patient)\")\n 1530 logger.info(f\" Unique Search_Terms found: {unique_terms}\")\n 1531\n 1532 # Log top Search_Terms\n 1533 top_terms = result_df['Search_Term'].value_counts().head(5)\n 1534 logger.info(f\" Top 5 indications: {dict(top_terms)}\")\n 1535 else:\n 1536 logger.info(f\"Indication lookup complete: 0 matches from {total_patients} patients\")\n 1537\n 1538 return result_df\n 1539\n 1540\n 1541# Export public API\n 1542__all__ = [\n 1543 # Dataclasses\n 1544 \"ClusterSnomedCodes\",\n 1545 \"IndicationValidationResult\",\n 1546 \"DrugIndicationMatchRate\",\n 1547 \"DrugSnomedMapping\",\n 1548 \"DirectSnomedMatchResult\",\n 1549 \"DirectorateAssignment\",\n 1550 # Cluster-based lookup functions (existing)\n 1551 \"get_drug_clusters\",\n 1552 \"get_drug_cluster_ids\",\n 1553 \"get_cluster_snomed_codes\",\n 1554 \"patient_has_indication\",\n 1555 \"validate_indication\",\n 1556 \"get_indication_match_rate\",\n 1557 \"batch_validate_indications\",\n 1558 \"get_available_clusters\",\n 1559 # Direct SNOMED lookup functions (new)\n 1560 \"get_drug_snomed_codes\",\n 1561 \"patient_has_indication_direct\",\n 1562 # Diagnosis-based directorate assignment\n 1563 \"get_directorate_from_diagnosis\",\n 1564 # Batch lookup for indication groups\n 1565 \"batch_lookup_indication_groups\",\n 1566 # Drug-indication mapping from DimSearchTerm.csv\n 1567 \"SEARCH_TERM_MERGE_MAP\",\n 1568 \"load_drug_indication_mapping\",\n 1569 \"get_search_terms_for_drug\",\n 1570 # Snowflake-direct indication lookup (new approach)\n 1571 \"get_patient_indication_groups\",\n 1572 \"CLUSTER_MAPPING_SQL\",\n 1573]\n 1574\n\n\nWhenever 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.\n\n"}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"cffe6f08-ef04-42aa-9725-b7bda5124d8e","tool_use_result":{"type":"text","file":{"filePath":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\data_processing\\diagnosis_lookup.py","content":"\"\"\"\nDiagnosis lookup module for NHS Patient Pathway Analysis.\n\nProvides functions to validate patient indications by checking GP diagnosis records\nagainst SNOMED cluster codes. Uses the drug-to-cluster mapping from\ndrug_indication_clusters.csv and queries Snowflake for SNOMED codes and GP records.\n\nKey workflow:\n1. Get drug's valid indication clusters from local mapping\n2. Get all SNOMED codes for those clusters from Snowflake\n3. Check if patient has any of those SNOMED codes in GP records\n4. Report indication validation status\n\nIMPORTANT: HCD activity data indication codes are UNRELIABLE. This module uses\nGP/Primary Care data (PrimaryCareClinicalCoding) as the authoritative source.\n\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom datetime import date, datetime\nfrom pathlib import Path\nfrom typing import Optional, Callable, Any, cast, TYPE_CHECKING\nimport csv\n\nif TYPE_CHECKING:\n import pandas as pd\n\nfrom core.logging_config import get_logger\nfrom data_processing.database import DatabaseManager, default_db_manager\nfrom data_processing.snowflake_connector import (\n SnowflakeConnector,\n get_connector,\n is_snowflake_available,\n is_snowflake_configured,\n SNOWFLAKE_AVAILABLE,\n)\nfrom data_processing.cache import get_cache, is_cache_enabled\n\nlogger = get_logger(__name__)\n\n\n@dataclass\nclass ClusterSnomedCodes:\n \"\"\"SNOMED codes for a clinical coding cluster.\"\"\"\n cluster_id: str\n cluster_description: str\n snomed_codes: list[str] = field(default_factory=list)\n snomed_descriptions: dict[str, str] = field(default_factory=dict)\n\n @property\n def code_count(self) -> int:\n return len(self.snomed_codes)\n\n\n@dataclass\nclass IndicationValidationResult:\n \"\"\"Result of validating a patient's indication for a drug.\"\"\"\n patient_pseudonym: str\n drug_name: str\n has_valid_indication: bool\n matched_cluster_id: Optional[str] = None\n matched_snomed_code: Optional[str] = None\n matched_snomed_description: Optional[str] = None\n checked_clusters: list[str] = field(default_factory=list)\n total_codes_checked: int = 0\n source: str = \"GP_SNOMED\" # GP_SNOMED | NONE\n error_message: Optional[str] = None\n\n\n@dataclass\nclass DrugIndicationMatchRate:\n \"\"\"Match rate statistics for a drug's indication validation.\"\"\"\n drug_name: str\n total_patients: int\n patients_with_indication: int\n patients_without_indication: int\n match_rate: float # 0.0 to 1.0\n clusters_checked: list[str] = field(default_factory=list)\n sample_unmatched: list[str] = field(default_factory=list) # Sample patient IDs\n\n\n@dataclass\nclass DrugSnomedMapping:\n \"\"\"SNOMED code mapping for a drug from ref_drug_snomed_mapping.\"\"\"\n snomed_code: str\n snomed_description: str\n search_term: str\n primary_directorate: str\n indication: str = \"\"\n ta_id: str = \"\"\n\n\n@dataclass\nclass DirectSnomedMatchResult:\n \"\"\"Result of direct SNOMED code lookup in GP records.\"\"\"\n patient_pseudonym: str\n matched: bool\n snomed_code: Optional[str] = None\n snomed_description: Optional[str] = None\n search_term: Optional[str] = None\n primary_directorate: Optional[str] = None\n event_date: Optional[datetime] = None\n source: str = \"DIRECT_SNOMED\" # DIRECT_SNOMED | NONE\n\n\n@dataclass\nclass DirectorateAssignment:\n \"\"\"Result of directorate assignment for a patient-drug combination.\"\"\"\n upid: str\n drug_name: str\n directorate: Optional[str]\n search_term: Optional[str] = None\n source: str = \"FALLBACK\" # DIAGNOSIS | FALLBACK\n snomed_code: Optional[str] = None\n event_date: Optional[datetime] = None\n\n\ndef get_drug_clusters(\n drug_name: str,\n db_manager: Optional[DatabaseManager] = None\n) -> list[dict]:\n \"\"\"\n Get all SNOMED cluster mappings for a drug from local SQLite.\n\n Args:\n drug_name: Drug name to look up (case-insensitive)\n db_manager: Optional DatabaseManager (defaults to default_db_manager)\n\n Returns:\n List of dicts with keys: drug_name, indication, cluster_id,\n cluster_description, nice_ta_reference\n \"\"\"\n if db_manager is None:\n db_manager = default_db_manager\n\n query = \"\"\"\n SELECT drug_name, indication, cluster_id, cluster_description, nice_ta_reference\n FROM ref_drug_indication_clusters\n WHERE UPPER(drug_name) = UPPER(?)\n ORDER BY indication, cluster_id\n \"\"\"\n\n try:\n with db_manager.get_connection() as conn:\n cursor = conn.execute(query, (drug_name,))\n rows = cursor.fetchall()\n\n results = []\n for row in rows:\n results.append({\n \"drug_name\": row[\"drug_name\"],\n \"indication\": row[\"indication\"],\n \"cluster_id\": row[\"cluster_id\"],\n \"cluster_description\": row[\"cluster_description\"],\n \"nice_ta_reference\": row[\"nice_ta_reference\"],\n })\n\n logger.debug(f\"Found {len(results)} cluster mappings for drug '{drug_name}'\")\n return results\n\n except Exception as e:\n logger.error(f\"Error getting clusters for drug '{drug_name}': {e}\")\n return []\n\n\ndef get_drug_cluster_ids(\n drug_name: str,\n db_manager: Optional[DatabaseManager] = None\n) -> list[str]:\n \"\"\"\n Get unique cluster IDs for a drug.\n\n Args:\n drug_name: Drug name to look up\n db_manager: Optional DatabaseManager\n\n Returns:\n List of unique cluster IDs\n \"\"\"\n clusters = get_drug_clusters(drug_name, db_manager)\n return list(set(c[\"cluster_id\"] for c in clusters))\n\n\ndef get_drug_snomed_codes(\n drug_name: str,\n db_manager: Optional[DatabaseManager] = None\n) -> list[DrugSnomedMapping]:\n \"\"\"\n Get all SNOMED codes for a drug from local ref_drug_snomed_mapping table.\n\n This uses the enriched mapping CSV data loaded into SQLite, which provides\n direct SNOMED-to-drug mappings with Search_Term and PrimaryDirectorate.\n\n Args:\n drug_name: Drug name to look up (case-insensitive, matches cleaned_drug_name)\n db_manager: Optional DatabaseManager (defaults to default_db_manager)\n\n Returns:\n List of DrugSnomedMapping with snomed_code, snomed_description,\n search_term, primary_directorate, indication, ta_id\n \"\"\"\n if db_manager is None:\n db_manager = default_db_manager\n\n query = \"\"\"\n SELECT DISTINCT\n snomed_code,\n snomed_description,\n search_term,\n primary_directorate,\n indication,\n ta_id\n FROM ref_drug_snomed_mapping\n WHERE UPPER(cleaned_drug_name) = UPPER(?)\n OR UPPER(drug_name) = UPPER(?)\n ORDER BY search_term, snomed_code\n \"\"\"\n\n try:\n with db_manager.get_connection() as conn:\n cursor = conn.execute(query, (drug_name, drug_name))\n rows = cursor.fetchall()\n\n results = []\n for row in rows:\n results.append(DrugSnomedMapping(\n snomed_code=row[\"snomed_code\"],\n snomed_description=row[\"snomed_description\"] or \"\",\n search_term=row[\"search_term\"] or \"\",\n primary_directorate=row[\"primary_directorate\"] or \"\",\n indication=row[\"indication\"] or \"\",\n ta_id=row[\"ta_id\"] or \"\",\n ))\n\n logger.debug(f\"Found {len(results)} SNOMED mappings for drug '{drug_name}'\")\n return results\n\n except Exception as e:\n logger.error(f\"Error getting SNOMED codes for drug '{drug_name}': {e}\")\n return []\n\n\ndef patient_has_indication_direct(\n patient_pseudonym: str,\n drug_snomed_mappings: list[DrugSnomedMapping],\n connector: Optional[SnowflakeConnector] = None,\n before_date: Optional[date] = None,\n) -> DirectSnomedMatchResult:\n \"\"\"\n Check if patient has any of the SNOMED codes in their GP records.\n\n This is the direct SNOMED lookup - it queries PrimaryCareClinicalCoding\n for exact SNOMED code matches (not via cluster). Returns the most recent\n match by EventDateTime if multiple matches exist.\n\n Args:\n patient_pseudonym: Patient's pseudonymised NHS number\n drug_snomed_mappings: List of DrugSnomedMapping from get_drug_snomed_codes()\n connector: Optional SnowflakeConnector (defaults to singleton)\n before_date: Optional date - only check diagnoses before this date\n\n Returns:\n DirectSnomedMatchResult with match details (most recent by EventDateTime)\n \"\"\"\n result = DirectSnomedMatchResult(\n patient_pseudonym=patient_pseudonym,\n matched=False,\n source=\"NONE\",\n )\n\n if not drug_snomed_mappings:\n return result\n\n if not SNOWFLAKE_AVAILABLE:\n logger.warning(\"Snowflake connector not available\")\n return result\n\n if not is_snowflake_configured():\n logger.warning(\"Snowflake not configured - cannot check GP records\")\n return result\n\n if connector is None:\n connector = get_connector()\n\n # Build lookup dict for mapping snomed_code -> (search_term, primary_directorate, snomed_description)\n snomed_lookup = {\n m.snomed_code: (m.search_term, m.primary_directorate, m.snomed_description)\n for m in drug_snomed_mappings\n }\n\n # Get unique SNOMED codes\n snomed_codes = list(snomed_lookup.keys())\n\n # Build placeholders for SNOMED codes\n placeholders = \", \".join([\"%s\"] * len(snomed_codes))\n\n # Query to find most recent matching SNOMED code in GP records\n query = f'''\n SELECT\n \"SNOMEDCode\",\n \"EventDateTime\"\n FROM DATA_HUB.PHM.\"PrimaryCareClinicalCoding\"\n WHERE \"PatientPseudonym\" = %s\n AND \"SNOMEDCode\" IN ({placeholders})\n '''\n\n params: list = [patient_pseudonym] + snomed_codes\n\n if before_date:\n query += ' AND \"EventDateTime\" < %s'\n params.append(before_date.isoformat())\n\n query += ' ORDER BY \"EventDateTime\" DESC LIMIT 1'\n\n try:\n results = connector.execute_dict(query, tuple(params))\n\n if results:\n row = results[0]\n matched_code = row.get(\"SNOMEDCode\")\n event_dt = row.get(\"EventDateTime\")\n\n if matched_code and matched_code in snomed_lookup:\n search_term, primary_dir, snomed_desc = snomed_lookup[matched_code]\n\n return DirectSnomedMatchResult(\n patient_pseudonym=patient_pseudonym,\n matched=True,\n snomed_code=matched_code,\n snomed_description=snomed_desc,\n search_term=search_term,\n primary_directorate=primary_dir,\n event_date=event_dt,\n source=\"DIRECT_SNOMED\",\n )\n\n return result\n\n except Exception as e:\n logger.error(f\"Error checking direct SNOMED for patient '{patient_pseudonym}': {e}\")\n return result\n\n\ndef get_directorate_from_diagnosis(\n upid: str,\n drug_name: str,\n connector: Optional[SnowflakeConnector] = None,\n db_manager: Optional[DatabaseManager] = None,\n before_date: Optional[date] = None,\n) -> DirectorateAssignment:\n \"\"\"\n Get directorate assignment for a patient-drug combination using diagnosis-based lookup.\n\n This function attempts to assign a directorate based on the patient's GP records\n (direct SNOMED code matching). If no match is found, it returns a FALLBACK result\n indicating that the caller should use alternative assignment methods (e.g.,\n department_identification() from tools/data.py).\n\n Workflow:\n 1. Get all SNOMED codes for the drug from ref_drug_snomed_mapping\n 2. Query patient's GP records for matching SNOMED codes\n 3. If match found  return diagnosis-based directorate and search_term\n 4. If no match  return FALLBACK result (caller handles fallback logic)\n\n Args:\n upid: Patient's unique patient ID (Provider Code[:3] + PersonKey)\n drug_name: Drug name to look up\n connector: Optional SnowflakeConnector (defaults to singleton)\n db_manager: Optional DatabaseManager (defaults to default_db_manager)\n before_date: Optional date - only check diagnoses before this date\n\n Returns:\n DirectorateAssignment with directorate, search_term, and source\n \"\"\"\n result = DirectorateAssignment(\n upid=upid,\n drug_name=drug_name,\n directorate=None,\n source=\"FALLBACK\",\n )\n\n # Step 1: Get SNOMED codes for the drug\n drug_snomed_mappings = get_drug_snomed_codes(drug_name, db_manager)\n\n if not drug_snomed_mappings:\n logger.debug(f\"No SNOMED mappings found for drug '{drug_name}' - using fallback\")\n return result\n\n # Step 2: Check Snowflake availability\n if not SNOWFLAKE_AVAILABLE:\n logger.debug(\"Snowflake not available - using fallback\")\n return result\n\n if not is_snowflake_configured():\n logger.debug(\"Snowflake not configured - using fallback\")\n return result\n\n # Step 3: Get patient pseudonym from UPID\n # UPID format is Provider Code (3 chars) + PersonKey\n # We need to query Snowflake to get the PatientPseudonym for this PersonKey\n # However, patient_has_indication_direct expects PatientPseudonym, not UPID\n # For now, we'll use UPID as the identifier - the actual integration\n # will need to happen at the DataFrame level where we have PersonKey\n #\n # NOTE: This function will be called from the pipeline where we have\n # access to PatientPseudonym. The UPID is passed for logging/tracking.\n\n # Actually, looking at the pipeline, we need PatientPseudonym, not UPID.\n # The caller should pass the PatientPseudonym or we need to look it up.\n # For now, let's assume the caller will use this in a batch context\n # where they can map UPID -> PatientPseudonym.\n\n # Let me reconsider: the function signature takes UPID but we need\n # PatientPseudonym for Snowflake. In the pipeline context (fetch_and_transform_data),\n # we'll have the PersonKey column which IS the PatientPseudonym.\n # So UPID = ProviderCode[:3] + PersonKey, and PersonKey = PatientPseudonym.\n #\n # We can extract PatientPseudonym from UPID by removing the first 3 chars.\n patient_pseudonym = upid[3:] if len(upid) > 3 else upid\n\n # Step 4: Check patient's GP records for matching SNOMED codes\n match_result = patient_has_indication_direct(\n patient_pseudonym=patient_pseudonym,\n drug_snomed_mappings=drug_snomed_mappings,\n connector=connector,\n before_date=before_date,\n )\n\n if match_result.matched and match_result.primary_directorate:\n return DirectorateAssignment(\n upid=upid,\n drug_name=drug_name,\n directorate=match_result.primary_directorate,\n search_term=match_result.search_term,\n source=\"DIAGNOSIS\",\n snomed_code=match_result.snomed_code,\n event_date=match_result.event_date,\n )\n\n # No match found - return fallback result\n return result\n\n\ndef get_cluster_snomed_codes(\n cluster_id: str,\n connector: Optional[SnowflakeConnector] = None,\n use_cache: bool = True,\n) -> ClusterSnomedCodes:\n \"\"\"\n Get all SNOMED codes for a cluster from Snowflake.\n\n Queries the ClinicalCodingClusterSnomedCodes table to get all SNOMED codes\n that belong to the specified cluster.\n\n Args:\n cluster_id: Cluster ID to look up (e.g., 'RARTH_COD', 'PSORIASIS_COD')\n connector: Optional SnowflakeConnector (defaults to singleton)\n use_cache: Whether to use cached results (default True)\n\n Returns:\n ClusterSnomedCodes with list of SNOMED codes and descriptions\n \"\"\"\n if not SNOWFLAKE_AVAILABLE:\n logger.warning(\"Snowflake connector not available\")\n return ClusterSnomedCodes(cluster_id=cluster_id, cluster_description=\"\")\n\n if not is_snowflake_configured():\n logger.warning(\"Snowflake not configured - cannot get cluster codes\")\n return ClusterSnomedCodes(cluster_id=cluster_id, cluster_description=\"\")\n\n # Check cache first\n cache_key = f\"cluster_snomed_{cluster_id}\"\n if use_cache and is_cache_enabled():\n cache = get_cache()\n cached = cache.get(cache_key)\n if cached is not None and len(cached) > 0:\n logger.debug(f\"Using cached SNOMED codes for cluster '{cluster_id}'\")\n cached_dict = cached[0] # First element is our data dict\n return ClusterSnomedCodes(\n cluster_id=cluster_id,\n cluster_description=str(cached_dict.get(\"description\", \"\")),\n snomed_codes=list(cached_dict.get(\"codes\", [])),\n snomed_descriptions=dict(cached_dict.get(\"descriptions\", {})),\n )\n\n if connector is None:\n connector = get_connector()\n\n query = '''\n SELECT DISTINCT\n \"Cluster_ID\",\n \"Cluster_Description\",\n \"SNOMEDCode\",\n \"SNOMEDDescription\"\n FROM DATA_HUB.PHM.\"ClinicalCodingClusterSnomedCodes\"\n WHERE \"Cluster_ID\" = %s\n ORDER BY \"SNOMEDCode\"\n '''\n\n try:\n results = connector.execute_dict(query, (cluster_id,))\n\n if not results:\n logger.warning(f\"No SNOMED codes found for cluster '{cluster_id}'\")\n return ClusterSnomedCodes(cluster_id=cluster_id, cluster_description=\"\")\n\n codes = []\n descriptions = {}\n description = results[0].get(\"Cluster_Description\", \"\") if results else \"\"\n\n for row in results:\n code = row.get(\"SNOMEDCode\")\n if code:\n codes.append(code)\n descriptions[code] = row.get(\"SNOMEDDescription\", \"\")\n\n logger.info(f\"Found {len(codes)} SNOMED codes for cluster '{cluster_id}'\")\n\n # Cache the results (using query-based cache with fake params)\n if use_cache and is_cache_enabled():\n cache = get_cache()\n cache_data = [{\n \"description\": description,\n \"codes\": codes,\n \"descriptions\": descriptions,\n }]\n cache.set(cache_key, None, cache_data) # type: ignore[arg-type]\n\n return ClusterSnomedCodes(\n cluster_id=cluster_id,\n cluster_description=description,\n snomed_codes=codes,\n snomed_descriptions=descriptions,\n )\n\n except Exception as e:\n logger.error(f\"Error getting SNOMED codes for cluster '{cluster_id}': {e}\")\n return ClusterSnomedCodes(cluster_id=cluster_id, cluster_description=\"\")\n\n\ndef patient_has_indication(\n patient_pseudonym: str,\n cluster_ids: list[str],\n connector: Optional[SnowflakeConnector] = None,\n before_date: Optional[date] = None,\n) -> tuple[bool, Optional[str], Optional[str], Optional[str]]:\n \"\"\"\n Check if a patient has any SNOMED codes from the specified clusters in GP records.\n\n Args:\n patient_pseudonym: Patient's pseudonymised NHS number\n cluster_ids: List of cluster IDs to check against\n connector: Optional SnowflakeConnector\n before_date: Optional date - only check diagnoses before this date\n\n Returns:\n Tuple of (has_indication, matched_cluster_id, matched_snomed_code, matched_description)\n \"\"\"\n if not SNOWFLAKE_AVAILABLE or not is_snowflake_configured():\n return False, None, None, None\n\n if not cluster_ids:\n return False, None, None, None\n\n if connector is None:\n connector = get_connector()\n\n # Build placeholders for cluster IDs\n placeholders = \", \".join([\"%s\"] * len(cluster_ids))\n\n # Query to check if patient has any matching SNOMED code\n query = f'''\n SELECT\n pc.\"SNOMEDCode\",\n cc.\"Cluster_ID\",\n cc.\"SNOMEDDescription\"\n FROM DATA_HUB.PHM.\"PrimaryCareClinicalCoding\" pc\n INNER JOIN DATA_HUB.PHM.\"ClinicalCodingClusterSnomedCodes\" cc\n ON pc.\"SNOMEDCode\" = cc.\"SNOMEDCode\"\n WHERE pc.\"PatientPseudonym\" = %s\n AND cc.\"Cluster_ID\" IN ({placeholders})\n '''\n\n params = [patient_pseudonym] + cluster_ids\n\n if before_date:\n query += ' AND pc.\"EventDateTime\" < %s'\n params.append(before_date.isoformat())\n\n query += ' LIMIT 1'\n\n try:\n results = connector.execute_dict(query, tuple(params))\n\n if results:\n row = results[0]\n return (\n True,\n row.get(\"Cluster_ID\"),\n row.get(\"SNOMEDCode\"),\n row.get(\"SNOMEDDescription\"),\n )\n\n return False, None, None, None\n\n except Exception as e:\n logger.error(f\"Error checking indication for patient '{patient_pseudonym}': {e}\")\n return False, None, None, None\n\n\ndef validate_indication(\n patient_pseudonym: str,\n drug_name: str,\n connector: Optional[SnowflakeConnector] = None,\n db_manager: Optional[DatabaseManager] = None,\n before_date: Optional[date] = None,\n) -> IndicationValidationResult:\n \"\"\"\n Validate that a patient has an appropriate indication for a drug.\n\n Full validation workflow:\n 1. Get drug's valid indication clusters from local mapping\n 2. Check if patient has any matching SNOMED codes in GP records\n 3. Return detailed validation result\n\n Args:\n patient_pseudonym: Patient's pseudonymised NHS number\n drug_name: Drug name to validate indication for\n connector: Optional SnowflakeConnector\n db_manager: Optional DatabaseManager\n before_date: Optional date - only check diagnoses before this date\n\n Returns:\n IndicationValidationResult with validation details\n \"\"\"\n result = IndicationValidationResult(\n patient_pseudonym=patient_pseudonym,\n drug_name=drug_name,\n has_valid_indication=False,\n )\n\n # Step 1: Get drug's cluster mappings\n cluster_ids = get_drug_cluster_ids(drug_name, db_manager)\n\n if not cluster_ids:\n result.error_message = f\"No cluster mappings found for drug '{drug_name}'\"\n result.source = \"NONE\"\n return result\n\n result.checked_clusters = cluster_ids\n\n # Step 2: Check Snowflake availability\n if not SNOWFLAKE_AVAILABLE:\n result.error_message = \"Snowflake connector not installed\"\n result.source = \"NONE\"\n return result\n\n if not is_snowflake_configured():\n result.error_message = \"Snowflake not configured\"\n result.source = \"NONE\"\n return result\n\n # Step 3: Check patient GP records\n has_indication, matched_cluster, matched_code, matched_desc = patient_has_indication(\n patient_pseudonym=patient_pseudonym,\n cluster_ids=cluster_ids,\n connector=connector,\n before_date=before_date,\n )\n\n result.has_valid_indication = has_indication\n result.matched_cluster_id = matched_cluster\n result.matched_snomed_code = matched_code\n result.matched_snomed_description = matched_desc\n result.source = \"GP_SNOMED\" if has_indication else \"NONE\"\n\n return result\n\n\ndef get_indication_match_rate(\n drug_name: str,\n patient_pseudonyms: list[str],\n connector: Optional[SnowflakeConnector] = None,\n db_manager: Optional[DatabaseManager] = None,\n sample_unmatched_count: int = 10,\n) -> DrugIndicationMatchRate:\n \"\"\"\n Calculate indication match rate for a drug across a list of patients.\n\n Args:\n drug_name: Drug name to check\n patient_pseudonyms: List of patient pseudonymised NHS numbers\n connector: Optional SnowflakeConnector\n db_manager: Optional DatabaseManager\n sample_unmatched_count: Number of unmatched patient IDs to include in sample\n\n Returns:\n DrugIndicationMatchRate with match statistics\n \"\"\"\n if connector is None and SNOWFLAKE_AVAILABLE and is_snowflake_configured():\n connector = get_connector()\n\n cluster_ids = get_drug_cluster_ids(drug_name, db_manager)\n\n total = len(patient_pseudonyms)\n matched = 0\n unmatched = 0\n sample_unmatched: list[str] = []\n\n if not cluster_ids:\n logger.warning(f\"No cluster mappings for drug '{drug_name}' - all patients will be unmatched\")\n return DrugIndicationMatchRate(\n drug_name=drug_name,\n total_patients=total,\n patients_with_indication=0,\n patients_without_indication=total,\n match_rate=0.0,\n clusters_checked=[],\n sample_unmatched=patient_pseudonyms[:sample_unmatched_count],\n )\n\n for i, pseudonym in enumerate(patient_pseudonyms):\n if i > 0 and i % 100 == 0:\n logger.info(f\"Validating indications: {i}/{total} ({100*i/total:.1f}%)\")\n\n has_indication, _, _, _ = patient_has_indication(\n patient_pseudonym=pseudonym,\n cluster_ids=cluster_ids,\n connector=connector,\n )\n\n if has_indication:\n matched += 1\n else:\n unmatched += 1\n if len(sample_unmatched) < sample_unmatched_count:\n sample_unmatched.append(pseudonym)\n\n match_rate = matched / total if total > 0 else 0.0\n\n logger.info(f\"Indication match rate for '{drug_name}': {100*match_rate:.1f}% ({matched}/{total})\")\n\n return DrugIndicationMatchRate(\n drug_name=drug_name,\n total_patients=total,\n patients_with_indication=matched,\n patients_without_indication=unmatched,\n match_rate=match_rate,\n clusters_checked=cluster_ids,\n sample_unmatched=sample_unmatched,\n )\n\n\ndef batch_validate_indications(\n patient_drug_pairs: list[tuple[str, str]],\n connector: Optional[SnowflakeConnector] = None,\n db_manager: Optional[DatabaseManager] = None,\n progress_callback: Optional[Callable[[int, int], None]] = None,\n) -> list[IndicationValidationResult]:\n \"\"\"\n Validate indications for multiple patient-drug pairs efficiently.\n\n Args:\n patient_drug_pairs: List of (patient_pseudonym, drug_name) tuples\n connector: Optional SnowflakeConnector\n db_manager: Optional DatabaseManager\n progress_callback: Optional callback(current, total) for progress updates\n\n Returns:\n List of IndicationValidationResult for each pair\n \"\"\"\n results = []\n total = len(patient_drug_pairs)\n\n # Cache cluster lookups by drug\n drug_clusters_cache = {}\n\n for i, (pseudonym, drug_name) in enumerate(patient_drug_pairs):\n if progress_callback:\n progress_callback(i + 1, total)\n\n # Get clusters from cache or lookup\n drug_upper = drug_name.upper()\n if drug_upper not in drug_clusters_cache:\n drug_clusters_cache[drug_upper] = get_drug_cluster_ids(drug_name, db_manager)\n\n cluster_ids = drug_clusters_cache[drug_upper]\n\n if not cluster_ids:\n results.append(IndicationValidationResult(\n patient_pseudonym=pseudonym,\n drug_name=drug_name,\n has_valid_indication=False,\n source=\"NONE\",\n error_message=f\"No cluster mappings for drug '{drug_name}'\",\n ))\n continue\n\n # Check patient indication\n has_indication, matched_cluster, matched_code, matched_desc = patient_has_indication(\n patient_pseudonym=pseudonym,\n cluster_ids=cluster_ids,\n connector=connector,\n )\n\n results.append(IndicationValidationResult(\n patient_pseudonym=pseudonym,\n drug_name=drug_name,\n has_valid_indication=has_indication,\n matched_cluster_id=matched_cluster,\n matched_snomed_code=matched_code,\n matched_snomed_description=matched_desc,\n checked_clusters=cluster_ids,\n source=\"GP_SNOMED\" if has_indication else \"NONE\",\n ))\n\n matched_count = sum(1 for r in results if r.has_valid_indication)\n logger.info(f\"Batch validation complete: {matched_count}/{total} ({100*matched_count/total:.1f}%) with valid indications\")\n\n return results\n\n\ndef get_available_clusters(\n connector: Optional[SnowflakeConnector] = None,\n) -> list[dict]:\n \"\"\"\n Get list of all available SNOMED clusters from Snowflake.\n\n Returns:\n List of dicts with cluster_id, cluster_description, code_count\n \"\"\"\n if not SNOWFLAKE_AVAILABLE or not is_snowflake_configured():\n logger.warning(\"Snowflake not available - cannot list clusters\")\n return []\n\n if connector is None:\n connector = get_connector()\n\n query = '''\n SELECT\n \"Cluster_ID\",\n \"Cluster_Description\",\n COUNT(DISTINCT \"SNOMEDCode\") as code_count\n FROM DATA_HUB.PHM.\"ClinicalCodingClusterSnomedCodes\"\n GROUP BY \"Cluster_ID\", \"Cluster_Description\"\n ORDER BY \"Cluster_ID\"\n '''\n\n try:\n results = connector.execute_dict(query)\n\n clusters = []\n for row in results:\n clusters.append({\n \"cluster_id\": row.get(\"Cluster_ID\"),\n \"cluster_description\": row.get(\"Cluster_Description\"),\n \"code_count\": row.get(\"code_count\", 0),\n })\n\n logger.info(f\"Found {len(clusters)} available SNOMED clusters\")\n return clusters\n\n except Exception as e:\n logger.error(f\"Error getting available clusters: {e}\")\n return []\n\n\ndef batch_lookup_indication_groups(\n df: \"pd.DataFrame\",\n connector: Optional[SnowflakeConnector] = None,\n db_manager: Optional[DatabaseManager] = None,\n batch_size: int = 500,\n) -> \"pd.DataFrame\":\n \"\"\"\n Batch lookup GP diagnosis-based indication groups for a DataFrame of patients.\n\n This is the efficient batch version of get_directorate_from_diagnosis().\n Instead of querying Snowflake per patient, it batches the lookups for performance.\n\n Strategy:\n 1. Get all unique (PersonKey, Drug Name) pairs from DataFrame\n 2. For each unique drug, get all SNOMED codes from local SQLite\n 3. Build batched Snowflake queries to check GP records\n 4. Return indication_df mapping UPID  Indication_Group\n\n For unmatched patients, Indication_Group will be their Directory (with suffix).\n\n Args:\n df: DataFrame with columns: UPID, Drug Name, Directory, PersonKey\n connector: Optional SnowflakeConnector (defaults to singleton)\n db_manager: Optional DatabaseManager (defaults to default_db_manager)\n batch_size: Number of patients per Snowflake query batch\n\n Returns:\n DataFrame with columns: UPID, Indication_Group, Source\n - Indication_Group: Search_Term (if matched) or \"Directory (no GP dx)\" (if not)\n - Source: \"DIAGNOSIS\" or \"FALLBACK\"\n \"\"\"\n import pandas as pd\n\n if db_manager is None:\n db_manager = default_db_manager\n\n logger.info(f\"Starting batch indication lookup for {len(df)} records...\")\n\n # Step 1: Get unique (UPID, Drug Name, PseudoNHSNoLinked, Directory) combinations\n # We need PseudoNHSNoLinked to query Snowflake - this matches PatientPseudonym in GP records\n # Note: PersonKey is LocalPatientID which is provider-specific and does NOT match GP records\n if 'PseudoNHSNoLinked' not in df.columns:\n logger.error(\"DataFrame missing 'PseudoNHSNoLinked' column - cannot lookup GP records\")\n # Return fallback for all patients\n result_df = df[['UPID', 'Directory']].drop_duplicates().copy()\n result_df['Indication_Group'] = result_df['Directory'] + \" (no GP dx)\"\n result_df['Source'] = \"FALLBACK\"\n return result_df[['UPID', 'Indication_Group', 'Source']]\n\n # Get unique patient-drug combinations (we need one lookup per patient-drug pair)\n unique_pairs = df[['UPID', 'Drug Name', 'PseudoNHSNoLinked', 'Directory']].drop_duplicates()\n logger.info(f\"Found {len(unique_pairs)} unique patient-drug combinations\")\n\n # Step 2: Get all unique drugs and their SNOMED codes\n unique_drugs = unique_pairs['Drug Name'].unique()\n logger.info(f\"Building SNOMED lookup for {len(unique_drugs)} unique drugs...\")\n\n # Build drug -> list of DrugSnomedMapping dict\n drug_snomed_map: dict[str, list[DrugSnomedMapping]] = {}\n all_snomed_codes: set[str] = set()\n snomed_to_drug_searchterm: dict[str, list[tuple[str, str, str]]] = {} # snomed -> [(drug, search_term, primary_dir), ...]\n\n for drug_name in unique_drugs:\n mappings = get_drug_snomed_codes(drug_name, db_manager)\n drug_snomed_map[drug_name] = mappings\n\n for m in mappings:\n all_snomed_codes.add(m.snomed_code)\n if m.snomed_code not in snomed_to_drug_searchterm:\n snomed_to_drug_searchterm[m.snomed_code] = []\n snomed_to_drug_searchterm[m.snomed_code].append(\n (drug_name, m.search_term, m.primary_directorate)\n )\n\n logger.info(f\"Total SNOMED codes to check: {len(all_snomed_codes)}\")\n\n # Step 3: Check Snowflake availability\n if not SNOWFLAKE_AVAILABLE or not is_snowflake_configured():\n logger.warning(\"Snowflake not available - returning fallback for all patients\")\n result_df = unique_pairs[['UPID', 'Directory']].copy()\n result_df['Indication_Group'] = result_df['Directory'] + \" (no GP dx)\"\n result_df['Source'] = \"FALLBACK\"\n return result_df[['UPID', 'Indication_Group', 'Source']].drop_duplicates(subset=['UPID'])\n\n if connector is None:\n connector = get_connector()\n\n # Step 4: Query GP records for all patients in batches\n # The query finds the most recent matching SNOMED code for each patient\n\n # Get unique PseudoNHSNoLinked values (each = one patient in GP records)\n unique_patients = unique_pairs[['PseudoNHSNoLinked', 'UPID', 'Directory']].drop_duplicates(subset=['PseudoNHSNoLinked'])\n patient_pseudonyms = unique_patients['PseudoNHSNoLinked'].tolist()\n\n logger.info(f\"Querying GP records for {len(patient_pseudonyms)} unique patients in batches of {batch_size}...\")\n\n # Results dict: PersonKey -> (snomed_code, event_date)\n gp_matches: dict[str, tuple[str, Any]] = {}\n\n # Convert SNOMED codes to list for query\n snomed_list = list(all_snomed_codes)\n\n if not snomed_list:\n logger.warning(\"No SNOMED codes to check - returning fallback for all patients\")\n result_df = unique_pairs[['UPID', 'Directory']].copy()\n result_df['Indication_Group'] = result_df['Directory'] + \" (no GP dx)\"\n result_df['Source'] = \"FALLBACK\"\n return result_df[['UPID', 'Indication_Group', 'Source']].drop_duplicates(subset=['UPID'])\n\n # Build SNOMED IN clause (reused across batches)\n snomed_placeholders = \", \".join([\"%s\"] * len(snomed_list))\n\n # Process patients in batches\n for batch_start in range(0, len(patient_pseudonyms), batch_size):\n batch_end = min(batch_start + batch_size, len(patient_pseudonyms))\n batch_pseudonyms = patient_pseudonyms[batch_start:batch_end]\n\n logger.info(f\"Batch {batch_start//batch_size + 1}: patients {batch_start} to {batch_end}\")\n\n # Build patient IN clause\n patient_placeholders = \", \".join([\"%s\"] * len(batch_pseudonyms))\n\n # Query to find all matching SNOMED codes for these patients\n # We'll get all matches and pick the most recent per patient in Python\n query = f'''\n SELECT\n \"PatientPseudonym\",\n \"SNOMEDCode\",\n \"EventDateTime\"\n FROM DATA_HUB.PHM.\"PrimaryCareClinicalCoding\"\n WHERE \"PatientPseudonym\" IN ({patient_placeholders})\n AND \"SNOMEDCode\" IN ({snomed_placeholders})\n ORDER BY \"PatientPseudonym\", \"EventDateTime\" DESC\n '''\n\n params = tuple(batch_pseudonyms) + tuple(snomed_list)\n\n try:\n results = connector.execute_dict(query, params)\n\n # Process results - pick most recent per patient\n for row in results:\n person_key = row.get(\"PatientPseudonym\")\n snomed_code = row.get(\"SNOMEDCode\")\n event_date = row.get(\"EventDateTime\")\n\n if person_key and snomed_code:\n # Keep only if we haven't seen this patient yet (first = most recent due to ORDER BY)\n if person_key not in gp_matches:\n gp_matches[person_key] = (snomed_code, event_date)\n\n except Exception as e:\n logger.error(f\"Error querying GP records for batch: {e}\")\n # Continue with other batches\n\n logger.info(f\"Found GP matches for {len(gp_matches)} patients\")\n\n # Step 5: Build result DataFrame\n # For each unique_pair, determine Indication_Group based on match status\n results_list = []\n\n # We need to dedupe by UPID - a patient might be on multiple drugs\n # Strategy: For each UPID, use the most recent match (if any)\n upid_to_match: dict[str, tuple[str, str]] = {} # UPID -> (Indication_Group, Source)\n\n for _, row in unique_pairs.iterrows():\n upid = row['UPID']\n drug_name = row['Drug Name']\n patient_pseudonym = row['PseudoNHSNoLinked']\n directory = row['Directory']\n\n # Check if patient has GP match (using PseudoNHSNoLinked which matches PatientPseudonym in GP)\n if patient_pseudonym in gp_matches:\n matched_snomed, event_date = gp_matches[patient_pseudonym]\n\n # Find the search_term for this SNOMED code and drug\n # (A SNOMED code might map to multiple drugs with different search_terms)\n if matched_snomed in snomed_to_drug_searchterm:\n # Look for match with current drug first\n search_term = None\n for drug, st, pd in snomed_to_drug_searchterm[matched_snomed]:\n if drug.upper() == drug_name.upper():\n search_term = st\n break\n # If no drug-specific match, use any match\n if search_term is None:\n search_term = snomed_to_drug_searchterm[matched_snomed][0][1]\n\n # Only update if we don't have a match for this UPID yet\n if upid not in upid_to_match:\n upid_to_match[upid] = (search_term, \"DIAGNOSIS\")\n else:\n # Shouldn't happen but fallback just in case\n if upid not in upid_to_match:\n upid_to_match[upid] = (directory + \" (no GP dx)\", \"FALLBACK\")\n else:\n # No GP match - use fallback\n if upid not in upid_to_match:\n upid_to_match[upid] = (directory + \" (no GP dx)\", \"FALLBACK\")\n\n # Build result DataFrame\n for upid, (indication_group, source) in upid_to_match.items():\n results_list.append({\n 'UPID': upid,\n 'Indication_Group': indication_group,\n 'Source': source,\n })\n\n result_df = pd.DataFrame(results_list)\n\n # Log statistics\n diagnosis_count = len([s for s in result_df['Source'] if s == \"DIAGNOSIS\"])\n fallback_count = len([s for s in result_df['Source'] if s == \"FALLBACK\"])\n total = len(result_df)\n\n logger.info(f\"Indication lookup complete:\")\n logger.info(f\" Total unique patients: {total}\")\n logger.info(f\" DIAGNOSIS matches: {diagnosis_count} ({100*diagnosis_count/total:.1f}%)\")\n logger.info(f\" FALLBACK (no GP match): {fallback_count} ({100*fallback_count/total:.1f}%)\")\n\n return result_df\n\n\n# === Drug-to-indication mapping from DimSearchTerm.csv ===\n\n\n# Merge related Search_Terms into canonical names.\n# Asthma variants are clinically the same condition at different severity levels.\n# Urticaria is a separate condition  do NOT merge with asthma.\nSEARCH_TERM_MERGE_MAP: dict[str, str] = {\n \"allergic asthma\": \"asthma\",\n \"severe persistent allergic asthma\": \"asthma\",\n}\n\n\ndef load_drug_indication_mapping(\n csv_path: Optional[str] = None,\n) -> tuple[dict[str, list[str]], dict[str, list[str]]]:\n \"\"\"\n Load the drug-to-Search_Term mapping from DimSearchTerm.csv.\n\n Builds two lookup dicts:\n - fragment_to_search_terms: drug fragment (UPPERCASE) -> list of Search_Terms containing it\n - search_term_to_fragments: search_term -> list of drug fragments (UPPERCASE)\n\n DimSearchTerm.csv has columns: Search_Term, CleanedDrugName, PrimaryDirectorate\n CleanedDrugName is pipe-separated (e.g., \"ADALIMUMAB|GOLIMUMAB|IXEKIZUMAB\").\n\n Note: A Search_Term can appear multiple times with different PrimaryDirectorates\n (e.g., \"diabetes\" appears under both DIABETIC MEDICINE and OPHTHALMOLOGY).\n Drug fragments from all rows for the same Search_Term are combined.\n\n Asthma-related Search_Terms (\"allergic asthma\", \"severe persistent allergic asthma\")\n are merged into \"asthma\" to match the CLUSTER_MAPPING_SQL normalization.\n \"urticaria\" stays separate.\n\n Args:\n csv_path: Path to DimSearchTerm.csv. Defaults to data/DimSearchTerm.csv.\n\n Returns:\n Tuple of (fragment_to_search_terms, search_term_to_fragments)\n \"\"\"\n if csv_path is None:\n csv_path = str(Path(__file__).parent.parent / \"data\" / \"DimSearchTerm.csv\")\n\n fragment_to_search_terms: dict[str, list[str]] = {}\n search_term_to_fragments: dict[str, list[str]] = {}\n\n try:\n with open(csv_path, \"r\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n for row in reader:\n search_term = row.get(\"Search_Term\", \"\").strip()\n drug_names_raw = row.get(\"CleanedDrugName\", \"\").strip()\n\n # Normalize asthma variants to canonical \"asthma\"\n search_term = SEARCH_TERM_MERGE_MAP.get(search_term, search_term)\n\n if not search_term or not drug_names_raw:\n continue\n\n fragments = [frag.strip().upper() for frag in drug_names_raw.split(\"|\") if frag.strip()]\n\n # Build search_term -> fragments (accumulate for duplicate Search_Terms)\n if search_term not in search_term_to_fragments:\n search_term_to_fragments[search_term] = []\n for frag in fragments:\n if frag not in search_term_to_fragments[search_term]:\n search_term_to_fragments[search_term].append(frag)\n\n # Build fragment -> search_terms\n for frag in fragments:\n if frag not in fragment_to_search_terms:\n fragment_to_search_terms[frag] = []\n if search_term not in fragment_to_search_terms[frag]:\n fragment_to_search_terms[frag].append(search_term)\n\n logger.info(\n f\"Loaded drug-indication mapping: {len(search_term_to_fragments)} Search_Terms, \"\n f\"{len(fragment_to_search_terms)} drug fragments\"\n )\n\n except FileNotFoundError:\n logger.error(f\"DimSearchTerm.csv not found at {csv_path}\")\n except Exception as e:\n logger.error(f\"Error loading DimSearchTerm.csv: {e}\")\n\n return fragment_to_search_terms, search_term_to_fragments\n\n\ndef get_search_terms_for_drug(\n drug_name: str,\n search_term_to_fragments: dict[str, list[str]],\n) -> list[str]:\n \"\"\"\n Get all Search_Terms that list a given drug using substring matching.\n\n Checks if any drug fragment from DimSearchTerm is a SUBSTRING of the given\n drug name (case-insensitive). This handles both exact matches (ADALIMUMAB)\n and partial fragments (PEGYLATED, INHALED).\n\n Args:\n drug_name: HCD drug name (e.g., \"ADALIMUMAB 40MG\", \"PEGYLATED LIPOSOMAL DOXORUBICIN\")\n search_term_to_fragments: Mapping of search_term -> list of drug fragments\n\n Returns:\n List of Search_Terms whose drug fragments match the drug name\n \"\"\"\n drug_name_upper = drug_name.upper()\n matched_terms: list[str] = []\n\n for search_term, fragments in search_term_to_fragments.items():\n for frag in fragments:\n if frag in drug_name_upper:\n matched_terms.append(search_term)\n break # One matching fragment is enough for this Search_Term\n\n return matched_terms\n\n\n# === NEW APPROACH: Query Snowflake directly using cluster CTE ===\n\n# The cluster query mapping (embedded from snomed_indication_mapping_query.sql)\n# This maps Search_Term -> Cluster_ID for ~148 clinical conditions\nCLUSTER_MAPPING_SQL = \"\"\"\nWITH SearchTermClusters AS (\n SELECT Search_Term, Cluster_ID FROM (VALUES\n ('acute lymphoblastic leukaemia', 'HAEMCANMORPH_COD'),\n ('acute myeloid leukaemia', 'C19HAEMCAN_COD'),\n ('acute promyelocytic leukaemia', 'HAEMCANMORPH_COD'),\n ('asthma', 'AST_COD'),\n ('allergic rhinitis', 'MILDINTAST_COD'),\n ('alzheimer''s disease', 'DEMALZ_COD'),\n ('amyloidosis', 'AMYLOID_COD'),\n ('anaemia', 'eFI2_AnaemiaTimeSensitive'),\n ('anaplastic large cell lymphoma', 'C19HAEMCAN_COD'),\n ('apixaban', 'DOACCON_COD'),\n ('aplastic anaemia', 'eFI2_AnaemiaEver'),\n ('arthritis', 'eFI2_InflammatoryArthritis'),\n ('asthma', 'eFI2_Asthma'),\n ('atopic dermatitis', 'ATOPDERM_COD'),\n ('atrial fibrillation', 'eFI2_AtrialFibrillation'),\n ('attention deficit hyperactivity disorder', 'ADHD_COD'),\n ('bipolar disorder', 'MH_COD'),\n ('bladder', 'eFI2_UrinaryIncontinence'),\n ('breast cancer', 'BRCANSCR_COD'),\n ('cardiomyopathy', 'eFI2_HarmfulDrinking'),\n ('cardiovascular disease', 'CVDRISKASS_COD'),\n ('cervical cancer', 'CSDEC_COD'),\n ('cholangiocarcinoma', 'eFI2_Cancer'),\n ('chronic kidney disease', 'CKD_COD'),\n ('chronic liver disease', 'eFI2_LiverProblems'),\n ('chronic lymphocytic leukaemia', 'EPPHAEMCAN_COD'),\n ('chronic myeloid leukaemia', 'EPPHAEMCAN_COD'),\n ('chronic obstructive pulmonary disease', 'eFI2_COPD'),\n ('colon cancer', 'eFI2_Cancer'),\n ('colorectal cancer', 'GICANREF_COD'),\n ('constipation', 'CHRONCONSTIP_COD'),\n ('covid-19', 'POSSPOSTCOVID_COD'),\n ('crohn''s disease', 'eFI2_InflammatoryBowelDisease'),\n ('cutaneous t-cell lymphoma', 'C19HAEMCAN_COD'),\n ('cystic fibrosis', 'CUST_ICB_CYSTIC_FIBROSIS'),\n ('deep vein thrombosis', 'VTE_COD'),\n ('depression', 'eFI2_Depression'),\n ('diabetes', 'eFI2_DiabetesEver'),\n ('diabetic retinopathy', 'DRSELIGIBILITY_COD'),\n ('diffuse large b-cell lymphoma', 'C19HAEMCAN_COD'),\n ('dravet syndrome', 'EPIL_COD'),\n ('drug misuse', 'ILLSUBINT_COD'),\n ('dyspepsia', 'eFI2_AbdominalPain'),\n ('epilepsy', 'eFI2_Seizures'),\n ('fallopian tube', 'STERIL_COD'),\n ('follicular lymphoma', 'C19HAEMCAN_COD'),\n ('gastric cancer', 'eFI2_Cancer'),\n ('giant cell arteritis', 'GCA_COD'),\n ('glioma', 'NHAEMCANMORPH_COD'),\n ('gout', 'eFI2_InflammatoryArthritis'),\n ('graft versus host disease', 'GVHD_COD'),\n ('granulomatosis with polyangiitis', 'WEGENERVASC_COD'),\n ('growth hormone deficiency', 'HYPOPITUITARY_COD'),\n ('hand eczema', 'ECZEMA_COD'),\n ('heart failure', 'eFI2_HeartFailure'),\n ('hepatitis b', 'HEPBCVAC_COD'),\n ('hepatocellular carcinoma', 'eFI2_Cancer'),\n ('hiv', 'PREFLANG_COD'),\n ('hodgkin lymphoma', 'HAEMCANMORPH_COD'),\n ('hormone receptor', 'eFI2_ThyroidProblems'),\n ('hypercholesterolaemia', 'CLASSFH_COD'),\n ('immune thrombocytopenia', 'ITP_COD'),\n ('influenza', 'FLUINVITE_COD'),\n ('insomnia', 'eFI2_SleepProblems'),\n ('irritable bowel syndrome', 'IBS_COD'),\n ('ischaemic stroke', 'OSTR_COD'),\n ('juvenile idiopathic arthritis', 'RARTHAD_COD'),\n ('kidney transplant', 'RENALTRANSP_COD'),\n ('leukaemia', 'eFI2_Cancer'),\n ('lung cancer', 'FTCANREF_COD'),\n ('lymphoma', 'C19HAEMCAN_COD'),\n ('macular degeneration', 'CUST_ICB_VISUAL_IMPAIRMENT'),\n ('macular oedema', 'CUST_ICB_VISUAL_IMPAIRMENT'),\n ('major depressive episodes', 'eFI2_Depression'),\n ('malignant melanoma', 'eFI2_Cancer'),\n ('malignant pleural mesothelioma', 'LUNGCAN_COD'),\n ('manic episode', 'MH_COD'),\n ('mantle cell lymphoma', 'HAEMCANMORPH_COD'),\n ('melanoma', 'eFI2_Cancer'),\n ('merkel cell carcinoma', 'C19CAN_COD'),\n ('migraine', 'eFI2_Headache'),\n ('motor neurone disease', 'MND_COD'),\n ('multiple myeloma', 'C19HAEMCAN_COD'),\n ('multiple sclerosis', 'MS_COD'),\n ('myelodysplastic', 'eFI2_AnaemiaEver'),\n ('myelofibrosis', 'MDS_COD'),\n ('myocardial infarction', 'eFI2_IschaemicHeartDisease'),\n ('myotonia', 'CNDATRISK2_COD'),\n ('narcolepsy', 'LD_COD'),\n ('neuroendocrine tumour', 'LUNGCAN_COD'),\n ('non-small cell lung cancer', 'LUNGCAN_COD'),\n ('non-small-cell lung cancer', 'FTCANREF_COD'),\n ('obesity', 'BMI30_COD'),\n ('osteoarthritis', 'CUST_ICB_OSTEOARTHRITIS'),\n ('osteoporosis', 'eFI2_Osteoporosis'),\n ('osteosarcoma', 'NHAEMCANMORPH_COD'),\n ('ovarian cancer', 'C19CAN_COD'),\n ('peripheral arterial disease', 'PADEXC_COD'),\n ('plaque psoriasis', 'PSORIASIS_COD'),\n ('polycystic kidney disease', 'EPPCONGMALF_COD'),\n ('polycythaemia vera', 'C19HAEMCAN_COD'),\n ('pregnancy', 'C19PREG_COD'),\n ('primary biliary cholangitis', 'eFI2_LiverProblems'),\n ('primary hypercholesterolaemia', 'FNFHYP_COD'),\n ('prostate cancer', 'EPPSOLIDCAN_COD'),\n ('psoriasis', 'PSORIASIS_COD'),\n ('psoriatic arthritis', 'RARTHAD_COD'),\n ('pulmonary embolism', 'eFI2_RespiratoryDiseaseTimeSensitive'),\n ('pulmonary fibrosis', 'ILD_COD'),\n ('relapsing multiple sclerosis', 'MS_COD'),\n ('renal cell carcinoma', 'C19CAN_COD'),\n ('renal transplantation', 'RENALTRANSP_COD'),\n ('retinal vein occlusion', 'CUST_ICB_VISUAL_IMPAIRMENT'),\n ('rheumatoid arthritis', 'eFI2_InflammatoryArthritis'),\n ('rivaroxaban', 'DOACCON_COD'),\n ('schizophrenia', 'MH_COD'),\n ('seizures', 'LSZFREQ_COD'),\n ('sepsis', 'C19ACTIVITY_COD'),\n ('asthma', 'SEVAST_COD'),\n ('sickle cell disease', 'SICKLE_COD'),\n ('sleep apnoea', 'CUST_ICB_NON_SEVERE_LDA'),\n ('smoking cessation', 'SMOKINGINT_COD'),\n ('soft tissue sarcoma', 'NHAEMCANMORPH_COD'),\n ('spinal muscular atrophy', 'MND_COD'),\n ('squamous cell', 'C19CAN_COD'),\n ('squamous cell carcinoma', 'C19CAN_COD'),\n ('stem cell transplant', 'ALLOTRANSP_COD'),\n ('stroke', 'eFI2_Stroke'),\n ('systemic lupus erythematosus', 'SLUPUS_COD'),\n ('systemic mastocytosis', 'HAEMCANMORPH_COD'),\n ('thrombocytopenic purpura', 'TTP_COD'),\n ('thrombotic thrombocytopenic purpura', 'TTP_COD'),\n ('thyroid cancer', 'C19CAN_COD'),\n ('tophaceous gout', 'CUST_ICB_OSTEOARTHRITIS'),\n ('transitional cell carcinoma', 'C19CAN_COD'),\n ('type 1 diabetes', 'DMTYPE1_COD'),\n ('type 2 diabetes', 'DMTYPE2_COD'),\n ('ulcerative colitis', 'eFI2_InflammatoryBowelDisease'),\n ('urothelial carcinoma', 'NHAEMCANMORPH_COD'),\n ('urticaria', 'XSAL_COD'),\n ('uveitis', 'CUST_ICB_VISUAL_IMPAIRMENT'),\n ('vascular disease', 'CVDINVITE_COD'),\n ('vasculitis', 'CRYOGLOBVASC_COD')\n ) AS t(Search_Term, Cluster_ID)\n),\n\nClusterCodes AS (\n SELECT\n stc.Search_Term,\n c.\"SNOMEDCode\",\n c.\"SNOMEDDescription\"\n FROM SearchTermClusters stc\n JOIN DATA_HUB.PHM.\"ClinicalCodingClusterSnomedCodes\" c\n ON stc.Cluster_ID = c.\"Cluster_ID\"\n WHERE c.\"SNOMEDCode\" IS NOT NULL\n),\n\nExplicitCodes AS (\n SELECT Search_Term, SNOMEDCode, SNOMEDDescription FROM (VALUES\n ('acute coronary syndrome', '837091000000100', 'Manual mapping'),\n ('ankylosing spondylitis', '162930007', 'Manual mapping'),\n ('ankylosing spondylitis', '239805001', 'Manual mapping'),\n ('ankylosing spondylitis', '239810002', 'Manual mapping'),\n ('ankylosing spondylitis', '239811003', 'Manual mapping'),\n ('ankylosing spondylitis', '394990003', 'Manual mapping'),\n ('ankylosing spondylitis', '429712009', 'Manual mapping'),\n ('ankylosing spondylitis', '441562009', 'Manual mapping'),\n ('ankylosing spondylitis', '441680005', 'Manual mapping'),\n ('ankylosing spondylitis', '441930001', 'Manual mapping'),\n ('axial spondyloarthritis', '723116002', 'Manual mapping'),\n ('choroidal neovascularisation', '380621000000102', 'Manual mapping'),\n ('choroidal neovascularisation', '733124000', 'Manual mapping')\n ) AS t(Search_Term, SNOMEDCode, SNOMEDDescription)\n),\n\nAllIndicationCodes AS (\n SELECT Search_Term, \"SNOMEDCode\" AS SNOMEDCode, \"SNOMEDDescription\" AS SNOMEDDescription\n FROM ClusterCodes\n UNION ALL\n SELECT Search_Term, SNOMEDCode, SNOMEDDescription\n FROM ExplicitCodes\n)\n\"\"\"\n\n\ndef get_patient_indication_groups(\n patient_pseudonyms: list[str],\n connector: Optional[SnowflakeConnector] = None,\n batch_size: int = 500,\n earliest_hcd_date: Optional[str] = None,\n) -> \"pd.DataFrame\":\n \"\"\"\n Batch lookup GP diagnosis-based indication groups using Snowflake cluster query.\n\n Returns ALL matching Search_Terms per patient with code_frequency (count of\n matching SNOMED codes). This enables drug-aware indication matching where\n each drug is cross-referenced against the patient's GP diagnoses.\n\n The query:\n 1. Uses the cluster mapping CTE to get all Search_Term -> SNOMED code mappings\n 2. Joins with PrimaryCareClinicalCoding to find patients with matching codes\n 3. Groups by patient + Search_Term and counts matching codes (code_frequency)\n 4. Optionally restricts to GP codes from earliest_hcd_date onwards\n\n Args:\n patient_pseudonyms: List of PseudoNHSNoLinked values (matches PatientPseudonym in GP records)\n connector: Optional SnowflakeConnector (defaults to singleton)\n batch_size: Number of patients per Snowflake query batch (default 500)\n earliest_hcd_date: Optional ISO date string (YYYY-MM-DD). If provided, only\n counts GP codes from this date onwards. Should be MIN(Intervention Date)\n from the HCD DataFrame to restrict to the HCD data window.\n\n Returns:\n DataFrame with columns:\n - PatientPseudonym: The patient identifier (PseudoNHSNoLinked value)\n - Search_Term: The matched indication (e.g., \"rheumatoid arthritis\")\n - code_frequency: Count of matching SNOMED codes for this Search_Term\n\n Multiple rows per patient (one per matched Search_Term).\n Patients not found in results have no matching GP diagnosis.\n \"\"\"\n import pandas as pd\n\n logger.info(f\"Starting Snowflake-direct indication lookup for {len(patient_pseudonyms)} patients...\")\n if earliest_hcd_date:\n logger.info(f\" Restricting GP codes to >= {earliest_hcd_date}\")\n\n # Handle edge case: empty patient list\n if not patient_pseudonyms:\n logger.warning(\"Empty patient list provided\")\n return pd.DataFrame(columns=['PatientPseudonym', 'Search_Term', 'code_frequency'])\n\n # Check Snowflake availability\n if not SNOWFLAKE_AVAILABLE:\n logger.error(\"Snowflake connector not available - cannot lookup GP records\")\n return pd.DataFrame(columns=['PatientPseudonym', 'Search_Term', 'code_frequency'])\n\n if not is_snowflake_configured():\n logger.error(\"Snowflake not configured - cannot lookup GP records\")\n return pd.DataFrame(columns=['PatientPseudonym', 'Search_Term', 'code_frequency'])\n\n if connector is None:\n connector = get_connector()\n\n # Results list to collect all matches\n all_results: list[dict] = []\n\n # Process patients in batches\n total_patients = len(patient_pseudonyms)\n for batch_start in range(0, total_patients, batch_size):\n batch_end = min(batch_start + batch_size, total_patients)\n batch_pseudonyms = patient_pseudonyms[batch_start:batch_end]\n batch_num = batch_start // batch_size + 1\n total_batches = (total_patients + batch_size - 1) // batch_size\n\n logger.info(f\"Batch {batch_num}/{total_batches}: patients {batch_start + 1} to {batch_end}\")\n\n # Build patient IN clause placeholders\n patient_placeholders = \", \".join([\"%s\"] * len(batch_pseudonyms))\n\n # Build WHERE clause with optional date filter\n date_filter = \"\"\n if earliest_hcd_date:\n date_filter = f\"\\n AND pc.\\\"EventDateTime\\\" >= %s\"\n\n # Build the full query with cluster CTE\n # Returns ALL matching Search_Terms per patient with code_frequency\n # code_frequency = COUNT of matching SNOMED codes per Search_Term per patient\n query = f\"\"\"\n{CLUSTER_MAPPING_SQL}\nSELECT\n pc.\"PatientPseudonym\" AS \"PatientPseudonym\",\n aic.Search_Term AS \"Search_Term\",\n COUNT(*) AS \"code_frequency\"\nFROM DATA_HUB.PHM.\"PrimaryCareClinicalCoding\" pc\nINNER JOIN AllIndicationCodes aic\n ON pc.\"SNOMEDCode\" = aic.SNOMEDCode\nWHERE pc.\"PatientPseudonym\" IN ({patient_placeholders}){date_filter}\nGROUP BY pc.\"PatientPseudonym\", aic.Search_Term\n\"\"\"\n\n # Build params: patient pseudonyms + optional date\n params = list(batch_pseudonyms)\n if earliest_hcd_date:\n params.append(earliest_hcd_date)\n\n try:\n results = connector.execute_dict(query, tuple(params))\n\n for row in results:\n all_results.append({\n 'PatientPseudonym': row.get('PatientPseudonym'),\n 'Search_Term': row.get('Search_Term'),\n 'code_frequency': row.get('code_frequency', 0),\n })\n\n logger.debug(f\"Batch {batch_num}: found {len(results)} patient-indication matches\")\n\n except Exception as e:\n logger.error(f\"Error querying GP records for batch {batch_num}: {e}\")\n # Continue with other batches - partial results are better than none\n\n # Build result DataFrame\n result_df = pd.DataFrame(all_results)\n\n # Log summary statistics\n if len(result_df) > 0:\n unique_patients = result_df['PatientPseudonym'].nunique()\n total_rows = len(result_df)\n match_rate = 100 * unique_patients / total_patients\n unique_terms = result_df['Search_Term'].nunique()\n avg_indications = total_rows / unique_patients if unique_patients > 0 else 0\n logger.info(f\"Indication lookup complete:\")\n logger.info(f\" Total patients queried: {total_patients}\")\n logger.info(f\" Patients with GP match: {unique_patients} ({match_rate:.1f}%)\")\n logger.info(f\" Total patient-indication rows: {total_rows} (avg {avg_indications:.1f} per patient)\")\n logger.info(f\" Unique Search_Terms found: {unique_terms}\")\n\n # Log top Search_Terms\n top_terms = result_df['Search_Term'].value_counts().head(5)\n logger.info(f\" Top 5 indications: {dict(top_terms)}\")\n else:\n logger.info(f\"Indication lookup complete: 0 matches from {total_patients} patients\")\n\n return result_df\n\n\n# Export public API\n__all__ = [\n # Dataclasses\n \"ClusterSnomedCodes\",\n \"IndicationValidationResult\",\n \"DrugIndicationMatchRate\",\n \"DrugSnomedMapping\",\n \"DirectSnomedMatchResult\",\n \"DirectorateAssignment\",\n # Cluster-based lookup functions (existing)\n \"get_drug_clusters\",\n \"get_drug_cluster_ids\",\n \"get_cluster_snomed_codes\",\n \"patient_has_indication\",\n \"validate_indication\",\n \"get_indication_match_rate\",\n \"batch_validate_indications\",\n \"get_available_clusters\",\n # Direct SNOMED lookup functions (new)\n \"get_drug_snomed_codes\",\n \"patient_has_indication_direct\",\n # Diagnosis-based directorate assignment\n \"get_directorate_from_diagnosis\",\n # Batch lookup for indication groups\n \"batch_lookup_indication_groups\",\n # Drug-indication mapping from DimSearchTerm.csv\n \"SEARCH_TERM_MERGE_MAP\",\n \"load_drug_indication_mapping\",\n \"get_search_terms_for_drug\",\n # Snowflake-direct indication lookup (new approach)\n \"get_patient_indication_groups\",\n \"CLUSTER_MAPPING_SQL\",\n]\n","numLines":1574,"startLine":1,"totalLines":1574}}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01WH4YSKJEk2ajGUJJbkwifQ","type":"message","role":"assistant","content":[{"type":"text","text":"Good. I've read all the required files. Let me understand the current state:\n\n**Phase 1 is complete** (Tasks 1.1, 1.2, 1.3 all done). The next task is **Task 2.1: Create `assign_drug_indications()` function** ÔÇö this is the core drug-aware matching logic.\n\n**Why Task 2.1**: \n- All Phase 1 dependencies are complete (Snowflake query returns ALL matches with code_frequency, drug mapping loaded from CSV, asthma merged)\n- Task 2.1 is the foundation for Phase 2 ÔÇö Task 2.2 (tiebreaker logic) is naturally part of 2.1\n- This can be built and tested with mock data (no Snowflake needed)\n- Phase 3 (pipeline integration) depends on this function existing\n\nLet me read the current refresh_pathways.py to understand the integration point and how gp_matches_df is currently used."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":24242,"cache_read_input_tokens":82844,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":24242},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"d4bd4a94-98fa-4f76-8ef4-01b6dc6c0c1e"}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01WH4YSKJEk2ajGUJJbkwifQ","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01WViPVt2UTcRhMerW65Fe7P","name":"Read","input":{"file_path":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\cli\\refresh_pathways.py"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":24242,"cache_read_input_tokens":82844,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":24242},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"c05ea9b8-fab1-4745-bd1d-0992627435fb"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01WViPVt2UTcRhMerW65Fe7P","type":"tool_result","content":" 1\"\"\"\n 2CLI command for refreshing pathway data from Snowflake.\n 3\n 4This command fetches activity data from Snowflake, processes it through the\n 5pathway pipeline for all 6 date filter combinations, and stores the results\n 6in the SQLite pathway_nodes table. Supports two chart types:\n 7- \"directory\": Trust  Directory  Drug  Pathway (default)\n 8- \"indication\": Trust  Search_Term  Drug  Pathway (requires GP diagnosis lookup)\n 9\n 10Usage:\n 11 python -m cli.refresh_pathways\n 12 python -m cli.refresh_pathways --minimum-patients 10\n 13 python -m cli.refresh_pathways --provider-codes RGT,RM1\n 14 python -m cli.refresh_pathways --chart-type all\n 15 python -m cli.refresh_pathways --chart-type directory\n 16 python -m cli.refresh_pathways --dry-run\n 17\n 18Run `python -m cli.refresh_pathways --help` for full options.\n 19\"\"\"\n 20\n 21import argparse\n 22import json\n 23import sqlite3\n 24import sys\n 25import time\n 26import uuid\n 27from datetime import datetime\n 28from pathlib import Path\n 29from typing import Optional\n 30\n 31from core import PathConfig, default_paths\n 32from core.logging_config import get_logger, setup_logging\n 33from data_processing.database import DatabaseManager, DatabaseConfig\n 34from data_processing.schema import (\n 35 clear_pathway_nodes,\n 36 get_pathway_table_counts,\n 37 verify_pathway_tables_exist,\n 38 create_pathway_tables,\n 39)\n 40from data_processing.pathway_pipeline import (\n 41 ChartType,\n 42 DATE_FILTER_CONFIGS,\n 43 fetch_and_transform_data,\n 44 process_all_date_filters,\n 45 process_pathway_for_date_filter,\n 46 process_indication_pathway_for_date_filter,\n 47 extract_denormalized_fields,\n 48 extract_indication_fields,\n 49 convert_to_records,\n 50)\n 51from data_processing.diagnosis_lookup import get_patient_indication_groups\n 52\n 53logger = get_logger(__name__)\n 54\n 55\n 56def get_default_filters(paths: PathConfig) -> tuple[list[str], list[str], list[str]]:\n 57 \"\"\"\n 58 Load default filter values from reference files.\n 59\n 60 Returns:\n 61 Tuple of (trust_filter, drug_filter, directory_filter)\n 62 \"\"\"\n 63 import pandas as pd\n 64\n 65 # Load default trusts\n 66 trust_filter = []\n 67 if paths.default_trusts_csv.exists():\n 68 try:\n 69 trusts_df = pd.read_csv(paths.default_trusts_csv)\n 70 # Use the \"Name\" column which contains trust names\n 71 if 'Name' in trusts_df.columns:\n 72 trust_filter = trusts_df['Name'].dropna().tolist()\n 73 else:\n 74 # Fallback to first column if no Name column\n 75 trust_filter = trusts_df.iloc[:, 0].dropna().tolist()\n 76 logger.info(f\"Loaded {len(trust_filter)} default trusts\")\n 77 except Exception as e:\n 78 logger.warning(f\"Could not load default trusts: {e}\")\n 79\n 80 # Load default drugs (Include=1 in include.csv)\n 81 drug_filter = []\n 82 if paths.include_csv.exists():\n 83 try:\n 84 drugs_df = pd.read_csv(paths.include_csv)\n 85 if 'Include' in drugs_df.columns:\n 86 drug_filter = drugs_df[drugs_df['Include'] == 1].iloc[:, 0].dropna().tolist()\n 87 else:\n 88 # Assume first column contains drug names if no Include column\n 89 drug_filter = drugs_df.iloc[:, 0].dropna().tolist()\n 90 logger.info(f\"Loaded {len(drug_filter)} default drugs\")\n 91 except Exception as e:\n 92 logger.warning(f\"Could not load default drugs: {e}\")\n 93\n 94 # Load default directories\n 95 directory_filter = []\n 96 if paths.directory_list_csv.exists():\n 97 try:\n 98 dirs_df = pd.read_csv(paths.directory_list_csv)\n 99 # Assume first column contains directory names\n 100 directory_filter = dirs_df.iloc[:, 0].dropna().tolist()\n 101 logger.info(f\"Loaded {len(directory_filter)} default directories\")\n 102 except Exception as e:\n 103 logger.warning(f\"Could not load default directories: {e}\")\n 104\n 105 return trust_filter, drug_filter, directory_filter\n 106\n 107\n 108def insert_pathway_records(\n 109 conn: sqlite3.Connection,\n 110 records: list[dict],\n 111) -> int:\n 112 \"\"\"\n 113 Insert pathway records into pathway_nodes table.\n 114\n 115 Uses INSERT OR REPLACE to handle updates to existing records.\n 116\n 117 Args:\n 118 conn: SQLite connection\n 119 records: List of record dicts from convert_to_records()\n 120\n 121 Returns:\n 122 Number of records inserted\n 123 \"\"\"\n 124 if not records:\n 125 return 0\n 126\n 127 # Column order matching pathway_nodes schema (includes chart_type)\n 128 columns = [\n 129 'date_filter_id', 'chart_type', 'parents', 'ids', 'labels', 'level',\n 130 'value', 'cost', 'costpp', 'cost_pp_pa', 'colour',\n 131 'first_seen', 'last_seen', 'first_seen_parent', 'last_seen_parent',\n 132 'average_spacing', 'average_administered', 'avg_days',\n 133 'trust_name', 'directory', 'drug_sequence', 'data_refresh_id'\n 134 ]\n 135\n 136 placeholders = ', '.join(['?' for _ in columns])\n 137 column_names = ', '.join(columns)\n 138\n 139 insert_sql = f\"\"\"\n 140 INSERT OR REPLACE INTO pathway_nodes ({column_names})\n 141 VALUES ({placeholders})\n 142 \"\"\"\n 143\n 144 # Convert records to tuples in column order\n 145 rows = []\n 146 for record in records:\n 147 row = tuple(record.get(col) for col in columns)\n 148 rows.append(row)\n 149\n 150 cursor = conn.executemany(insert_sql, rows)\n 151 return cursor.rowcount\n 152\n 153\n 154def log_refresh_start(\n 155 conn: sqlite3.Connection,\n 156 refresh_id: str,\n 157 date_from: Optional[str] = None,\n 158 date_to: Optional[str] = None,\n 159) -> None:\n 160 \"\"\"Log the start of a refresh operation.\"\"\"\n 161 conn.execute(\"\"\"\n 162 INSERT INTO pathway_refresh_log\n 163 (refresh_id, started_at, status, snowflake_query_date_from, snowflake_query_date_to)\n 164 VALUES (?, ?, 'running', ?, ?)\n 165 \"\"\", (refresh_id, datetime.now().isoformat(), date_from, date_to))\n 166 conn.commit()\n 167\n 168\n 169def log_refresh_complete(\n 170 conn: sqlite3.Connection,\n 171 refresh_id: str,\n 172 record_count: int,\n 173 date_filter_counts: dict[str, int],\n 174 duration_seconds: float,\n 175) -> None:\n 176 \"\"\"Log the successful completion of a refresh operation.\"\"\"\n 177 conn.execute(\"\"\"\n 178 UPDATE pathway_refresh_log\n 179 SET completed_at = ?,\n 180 status = 'completed',\n 181 record_count = ?,\n 182 date_filter_counts = ?,\n 183 processing_duration_seconds = ?\n 184 WHERE refresh_id = ?\n 185 \"\"\", (\n 186 datetime.now().isoformat(),\n 187 record_count,\n 188 json.dumps(date_filter_counts),\n 189 duration_seconds,\n 190 refresh_id,\n 191 ))\n 192 conn.commit()\n 193\n 194\n 195def log_refresh_failed(\n 196 conn: sqlite3.Connection,\n 197 refresh_id: str,\n 198 error_message: str,\n 199 duration_seconds: float,\n 200) -> None:\n 201 \"\"\"Log a failed refresh operation.\"\"\"\n 202 conn.execute(\"\"\"\n 203 UPDATE pathway_refresh_log\n 204 SET completed_at = ?,\n 205 status = 'failed',\n 206 error_message = ?,\n 207 processing_duration_seconds = ?\n 208 WHERE refresh_id = ?\n 209 \"\"\", (\n 210 datetime.now().isoformat(),\n 211 error_message,\n 212 duration_seconds,\n 213 refresh_id,\n 214 ))\n 215 conn.commit()\n 216\n 217\n 218def refresh_pathways(\n 219 minimum_patients: int = 5,\n 220 provider_codes: Optional[list[str]] = None,\n 221 trust_filter: Optional[list[str]] = None,\n 222 drug_filter: Optional[list[str]] = None,\n 223 directory_filter: Optional[list[str]] = None,\n 224 db_path: Optional[Path] = None,\n 225 paths: Optional[PathConfig] = None,\n 226 dry_run: bool = False,\n 227 chart_type: str = \"directory\",\n 228) -> tuple[bool, str, dict]:\n 229 \"\"\"\n 230 Main refresh function that orchestrates the full pipeline.\n 231\n 232 Args:\n 233 minimum_patients: Minimum patients to include a pathway\n 234 provider_codes: List of provider codes to filter Snowflake query\n 235 trust_filter: List of trust names to include in pathways\n 236 drug_filter: List of drug names to include in pathways\n 237 directory_filter: List of directories to include in pathways\n 238 db_path: Path to SQLite database (uses default if None)\n 239 paths: PathConfig for file paths\n 240 dry_run: If True, don't actually insert records\n 241 chart_type: Which chart type to process: \"directory\", \"indication\", or \"all\"\n 242\n 243 Returns:\n 244 Tuple of (success: bool, message: str, stats: dict)\n 245 \"\"\"\n 246 if paths is None:\n 247 paths = default_paths\n 248\n 249 # Set up database connection\n 250 if db_path:\n 251 db_config = DatabaseConfig(db_path=db_path)\n 252 else:\n 253 db_config = DatabaseConfig(data_dir=paths.data_dir)\n 254\n 255 db_manager = DatabaseManager(db_config)\n 256\n 257 # Load default filters if not provided\n 258 default_trusts, default_drugs, default_dirs = get_default_filters(paths)\n 259\n 260 if trust_filter is None:\n 261 trust_filter = default_trusts\n 262 if drug_filter is None:\n 263 drug_filter = default_drugs\n 264 if directory_filter is None:\n 265 directory_filter = default_dirs\n 266\n 267 # Ensure we have some filters\n 268 if not drug_filter:\n 269 return False, \"No drugs specified and could not load defaults\", {}\n 270\n 271 # Determine which chart types to process\n 272 if chart_type == \"all\":\n 273 chart_types_to_process: list[ChartType] = [\"directory\", \"indication\"]\n 274 else:\n 275 chart_types_to_process = [chart_type] # type: ignore\n 276\n 277 logger.info(\"=\" * 60)\n 278 logger.info(\"Pathway Data Refresh Starting\")\n 279 logger.info(\"=\" * 60)\n 280 logger.info(f\"Minimum patients: {minimum_patients}\")\n 281 logger.info(f\"Trust filter: {len(trust_filter)} trusts\")\n 282 logger.info(f\"Drug filter: {len(drug_filter)} drugs\")\n 283 logger.info(f\"Directory filter: {len(directory_filter)} directories\")\n 284 logger.info(f\"Provider codes: {provider_codes or 'All'}\")\n 285 logger.info(f\"Chart type(s): {', '.join(chart_types_to_process)}\")\n 286 logger.info(f\"Database: {db_manager.db_path}\")\n 287 logger.info(f\"Dry run: {dry_run}\")\n 288 logger.info(\"=\" * 60)\n 289\n 290 start_time = time.time()\n 291 refresh_id = str(uuid.uuid4())[:8]\n 292 stats = {\n 293 \"refresh_id\": refresh_id,\n 294 \"date_filter_counts\": {},\n 295 \"total_records\": 0,\n 296 \"snowflake_rows\": 0,\n 297 }\n 298\n 299 try:\n 300 # Verify database and tables\n 301 with db_manager.get_connection() as conn:\n 302 missing_tables = verify_pathway_tables_exist(conn)\n 303 if missing_tables:\n 304 logger.info(f\"Creating missing tables: {missing_tables}\")\n 305 create_pathway_tables(conn)\n 306\n 307 # Log refresh start\n 308 if not dry_run:\n 309 log_refresh_start(conn, refresh_id)\n 310\n 311 # Step 1: Fetch data from Snowflake\n 312 logger.info(\"\")\n 313 logger.info(\"Step 1/4: Fetching data from Snowflake...\")\n 314 df = fetch_and_transform_data(\n 315 provider_codes=provider_codes,\n 316 paths=paths,\n 317 )\n 318\n 319 if df.empty:\n 320 msg = \"No data returned from Snowflake\"\n 321 logger.error(msg)\n 322 with db_manager.get_connection() as conn:\n 323 log_refresh_failed(conn, refresh_id, msg, time.time() - start_time)\n 324 return False, msg, stats\n 325\n 326 stats[\"snowflake_rows\"] = len(df)\n 327 logger.info(f\"Fetched {len(df)} records from Snowflake\")\n 328\n 329 # Step 2: Process all date filters for each chart type\n 330 num_date_filters = len(DATE_FILTER_CONFIGS)\n 331 num_chart_types = len(chart_types_to_process)\n 332 total_datasets = num_date_filters * num_chart_types\n 333\n 334 logger.info(\"\")\n 335 logger.info(f\"Step 2/4: Processing pathway data for {total_datasets} datasets \"\n 336 f\"({num_date_filters} date filters x {num_chart_types} chart types)...\")\n 337\n 338 # Store results keyed by \"date_filter_id:chart_type\"\n 339 results: dict[str, list[dict]] = {}\n 340\n 341 for current_chart_type in chart_types_to_process:\n 342 logger.info(\"\")\n 343 logger.info(f\"Processing chart type: {current_chart_type}\")\n 344\n 345 if current_chart_type == \"directory\":\n 346 # Use existing process_all_date_filters for directory charts\n 347 dir_results = process_all_date_filters(\n 348 df=df,\n 349 trust_filter=trust_filter,\n 350 drug_filter=drug_filter,\n 351 directory_filter=directory_filter,\n 352 minimum_patients=minimum_patients,\n 353 refresh_id=refresh_id,\n 354 paths=paths,\n 355 )\n 356 # Add results with chart_type suffix\n 357 for filter_id, records in dir_results.items():\n 358 # Records already have chart_type set by convert_to_records\n 359 results[f\"{filter_id}:directory\"] = records\n 360\n 361 elif current_chart_type == \"indication\":\n 362 # For indication charts, we need to look up GP diagnoses for all patients\n 363 # using the new Snowflake-direct approach via get_patient_indication_groups()\n 364 logger.info(\"Building indication groups from GP diagnosis lookups (Snowflake-direct)...\")\n 365\n 366 # Check Snowflake availability\n 367 from data_processing.snowflake_connector import get_connector, is_snowflake_available\n 368\n 369 if not is_snowflake_available():\n 370 logger.warning(\"Snowflake not available - cannot process indication charts\")\n 371 for config in DATE_FILTER_CONFIGS:\n 372 results[f\"{config.id}:indication\"] = []\n 373 continue\n 374\n 375 try:\n 376 import pandas as pd\n 377 connector = get_connector()\n 378\n 379 # Step 1: Extract unique PseudoNHSNoLinked values from df\n 380 # This is the patient identifier that matches PatientPseudonym in GP records\n 381 if 'PseudoNHSNoLinked' not in df.columns:\n 382 logger.error(\"DataFrame missing 'PseudoNHSNoLinked' column - cannot lookup GP records\")\n 383 for config in DATE_FILTER_CONFIGS:\n 384 results[f\"{config.id}:indication\"] = []\n 385 continue\n 386\n 387 # Get unique patient pseudonyms for GP lookup (avoid redundant queries)\n 388 patient_pseudonyms = df['PseudoNHSNoLinked'].dropna().unique().tolist()\n 389\n 390 logger.info(f\"Looking up GP diagnoses for {len(patient_pseudonyms)} unique patients...\")\n 391\n 392 # Step 2: Call the new Snowflake-direct indication lookup\n 393 gp_matches_df = get_patient_indication_groups(\n 394 patient_pseudonyms=patient_pseudonyms,\n 395 connector=connector,\n 396 batch_size=500,\n 397 )\n 398\n 399 # Step 3: Build indication_df mapping UPID -> Indication_Group\n 400 # For matched patients: Indication_Group = Search_Term\n 401 # For unmatched patients: Indication_Group = Directory + \" (no GP dx)\"\n 402 #\n 403 # IMPORTANT: We need ALL unique UPIDs, not just unique PseudoNHSNoLinked.\n 404 # A patient can have multiple UPIDs if they visited multiple providers.\n 405\n 406 # Get all unique UPID records with their PseudoNHSNoLinked and Directory\n 407 upid_lookup = df[['UPID', 'PseudoNHSNoLinked', 'Directory']].drop_duplicates(\n 408 subset=['UPID']\n 409 ).copy()\n 410\n 411 if gp_matches_df.empty:\n 412 logger.warning(\"No GP matches found - all patients will use fallback directory\")\n 413 # All patients use fallback\n 414 indication_records = []\n 415 for _, row in upid_lookup.iterrows():\n 416 directory = row['Directory']\n 417 indication_records.append({\n 418 'UPID': row['UPID'],\n 419 'Indication_Group': str(directory) + \" (no GP dx)\" if pd.notna(directory) else \"UNKNOWN (no GP dx)\",\n 420 'Source': 'FALLBACK',\n 421 })\n 422 indication_df = pd.DataFrame(indication_records)\n 423 else:\n 424 # Create lookup dict: PseudoNHSNoLinked -> Search_Term\n 425 match_lookup = dict(zip(\n 426 gp_matches_df['PatientPseudonym'],\n 427 gp_matches_df['Search_Term']\n 428 ))\n 429\n 430 # Build indication records for each unique UPID\n 431 indication_records = []\n 432 for _, row in upid_lookup.iterrows():\n 433 pseudo = row['PseudoNHSNoLinked']\n 434 upid = row['UPID']\n 435 directory = row['Directory']\n 436\n 437 if pd.notna(pseudo) and pseudo in match_lookup:\n 438 indication_records.append({\n 439 'UPID': upid,\n 440 'Indication_Group': match_lookup[pseudo],\n 441 'Source': 'DIAGNOSIS',\n 442 })\n 443 else:\n 444 # Use fallback: Directory + \" (no GP dx)\"\n 445 fallback_label = str(directory) + \" (no GP dx)\" if pd.notna(directory) else \"UNKNOWN (no GP dx)\"\n 446 indication_records.append({\n 447 'UPID': upid,\n 448 'Indication_Group': fallback_label,\n 449 'Source': 'FALLBACK',\n 450 })\n 451\n 452 indication_df = pd.DataFrame(indication_records)\n 453\n 454 # Log coverage statistics\n 455 if not indication_df.empty:\n 456 diagnosis_count = (indication_df['Source'] == 'DIAGNOSIS').sum()\n 457 fallback_count = (indication_df['Source'] == 'FALLBACK').sum()\n 458 total = len(indication_df)\n 459 stats[\"diagnosis_coverage\"] = {\n 460 \"diagnosis\": int(diagnosis_count),\n 461 \"fallback\": int(fallback_count),\n 462 \"total\": total,\n 463 \"diagnosis_pct\": round(100 * diagnosis_count / total, 1) if total > 0 else 0,\n 464 }\n 465 logger.info(f\"Indication coverage: {diagnosis_count}/{total} ({stats['diagnosis_coverage']['diagnosis_pct']}%) diagnosis-matched\")\n 466\n 467 # Log top indication groups\n 468 top_indications = indication_df[indication_df['Source'] == 'DIAGNOSIS']['Indication_Group'].value_counts().head(5)\n 469 if len(top_indications) > 0:\n 470 logger.info(f\"Top 5 indications: {dict(top_indications)}\")\n 471\n 472 # Rename column for compatibility with generate_icicle_chart_indication\n 473 # It expects indication_df to have 'Directory' column (mapped from Indication_Group)\n 474 indication_df_for_chart = indication_df[['UPID', 'Indication_Group']].copy()\n 475 indication_df_for_chart = indication_df_for_chart.rename(columns={'Indication_Group': 'Directory'})\n 476 # Ensure unique UPID index (build_hierarchy requires uniquely valued Index)\n 477 # Keep first occurrence - DIAGNOSIS entries should come before FALLBACK\n 478 indication_df_for_chart = indication_df_for_chart.drop_duplicates(subset=['UPID'], keep='first')\n 479 indication_df_for_chart = indication_df_for_chart.set_index('UPID')\n 480\n 481 # Process each date filter with indication grouping\n 482 for config in DATE_FILTER_CONFIGS:\n 483 logger.info(f\"Processing indication pathway for {config.id}\")\n 484\n 485 ice_df = process_indication_pathway_for_date_filter(\n 486 df=df,\n 487 indication_df=indication_df_for_chart,\n 488 config=config,\n 489 trust_filter=trust_filter,\n 490 drug_filter=drug_filter,\n 491 directory_filter=directory_filter,\n 492 minimum_patients=minimum_patients,\n 493 paths=paths,\n 494 )\n 495\n 496 if ice_df is None:\n 497 logger.warning(f\"No indication pathway data for {config.id}\")\n 498 results[f\"{config.id}:indication\"] = []\n 499 continue\n 500\n 501 # Extract denormalized fields (using indication variant)\n 502 ice_df = extract_indication_fields(ice_df)\n 503\n 504 # Convert to records with chart_type=\"indication\"\n 505 records = convert_to_records(ice_df, config.id, refresh_id, chart_type=\"indication\")\n 506 results[f\"{config.id}:indication\"] = records\n 507\n 508 logger.info(f\"Completed {config.id}:indication: {len(records)} nodes\")\n 509 else:\n 510 logger.warning(\"Empty indication_df - skipping indication charts\")\n 511 for config in DATE_FILTER_CONFIGS:\n 512 results[f\"{config.id}:indication\"] = []\n 513\n 514 except Exception as e:\n 515 logger.error(f\"Error processing indication charts: {e}\")\n 516 logger.exception(e)\n 517 for config in DATE_FILTER_CONFIGS:\n 518 results[f\"{config.id}:indication\"] = []\n 519\n 520 # Count records per filter and chart type\n 521 stats[\"chart_type_counts\"] = {}\n 522 for key, records in results.items():\n 523 stats[\"date_filter_counts\"][key] = len(records)\n 524 stats[\"total_records\"] += len(records)\n 525 # Also track by chart type\n 526 _, ct = key.split(\":\")\n 527 stats[\"chart_type_counts\"][ct] = stats[\"chart_type_counts\"].get(ct, 0) + len(records)\n 528\n 529 logger.info(\"\")\n 530 logger.info(f\"Processed {stats['total_records']} total pathway nodes\")\n 531 for chart_type_name, count in stats.get(\"chart_type_counts\", {}).items():\n 532 logger.info(f\" {chart_type_name}: {count} nodes total\")\n 533 for key, count in sorted(stats[\"date_filter_counts\"].items()):\n 534 if count > 0:\n 535 logger.info(f\" {key}: {count} nodes\")\n 536\n 537 if dry_run:\n 538 logger.info(\"\")\n 539 logger.info(\"DRY RUN - Skipping database insertion\")\n 540 elapsed = time.time() - start_time\n 541 return True, f\"Dry run complete: {stats['total_records']} records would be inserted\", stats\n 542\n 543 # Step 3: Clear existing data and insert new records\n 544 logger.info(\"\")\n 545 logger.info(\"Step 3/4: Clearing existing pathway data and inserting new records...\")\n 546\n 547 with db_manager.get_transaction() as conn:\n 548 # Clear all existing pathway nodes\n 549 deleted = clear_pathway_nodes(conn)\n 550 logger.info(f\"Cleared {deleted} existing pathway nodes\")\n 551\n 552 # Insert new records for each date filter + chart type combination\n 553 total_inserted = 0\n 554 for key, records in results.items():\n 555 if records:\n 556 inserted = insert_pathway_records(conn, records)\n 557 total_inserted += len(records)\n 558 logger.info(f\" Inserted {len(records)} records for {key}\")\n 559\n 560 # Step 4: Log completion\n 561 logger.info(\"\")\n 562 logger.info(\"Step 4/4: Logging refresh completion...\")\n 563\n 564 elapsed = time.time() - start_time\n 565\n 566 with db_manager.get_connection() as conn:\n 567 log_refresh_complete(\n 568 conn=conn,\n 569 refresh_id=refresh_id,\n 570 record_count=stats[\"total_records\"],\n 571 date_filter_counts=stats[\"date_filter_counts\"],\n 572 duration_seconds=elapsed,\n 573 )\n 574\n 575 # Verify final counts\n 576 counts = get_pathway_table_counts(conn)\n 577 logger.info(f\"Final table counts: {counts}\")\n 578\n 579 logger.info(\"\")\n 580 logger.info(\"=\" * 60)\n 581 logger.info(f\"Refresh completed successfully in {elapsed:.1f} seconds\")\n 582 logger.info(f\"Total records: {stats['total_records']}\")\n 583 logger.info(f\"Refresh ID: {refresh_id}\")\n 584 logger.info(\"=\" * 60)\n 585\n 586 return True, f\"Refresh complete: {stats['total_records']} records in {elapsed:.1f}s\", stats\n 587\n 588 except Exception as e:\n 589 elapsed = time.time() - start_time\n 590 error_msg = f\"Refresh failed: {e}\"\n 591 logger.error(error_msg, exc_info=True)\n 592\n 593 try:\n 594 with db_manager.get_connection() as conn:\n 595 log_refresh_failed(conn, refresh_id, str(e), elapsed)\n 596 except Exception:\n 597 pass # Don't fail the error handling\n 598\n 599 return False, error_msg, stats\n 600\n 601\n 602def main() -> int:\n 603 \"\"\"CLI entry point.\"\"\"\n 604 parser = argparse.ArgumentParser(\n 605 description=\"Refresh pathway data from Snowflake\",\n 606 formatter_class=argparse.RawDescriptionHelpFormatter,\n 607 epilog=\"\"\"\n 608Examples:\n 609 # Basic refresh with defaults (directory chart only)\n 610 python -m cli.refresh_pathways\n 611\n 612 # Refresh both chart types (directory and indication)\n 613 python -m cli.refresh_pathways --chart-type all\n 614\n 615 # Refresh only indication-based charts\n 616 python -m cli.refresh_pathways --chart-type indication\n 617\n 618 # Refresh with custom minimum patients\n 619 python -m cli.refresh_pathways --minimum-patients 10\n 620\n 621 # Refresh specific providers only\n 622 python -m cli.refresh_pathways --provider-codes RGT,RM1\n 623\n 624 # Dry run to see what would be processed\n 625 python -m cli.refresh_pathways --dry-run\n 626\n 627 # Verbose output\n 628 python -m cli.refresh_pathways --verbose\n 629 \"\"\"\n 630 )\n 631\n 632 parser.add_argument(\n 633 \"--minimum-patients\",\n 634 type=int,\n 635 default=5,\n 636 help=\"Minimum patients to include a pathway (default: 5)\"\n 637 )\n 638\n 639 parser.add_argument(\n 640 \"--provider-codes\",\n 641 type=str,\n 642 default=None,\n 643 help=\"Comma-separated list of provider codes to filter (default: all)\"\n 644 )\n 645\n 646 parser.add_argument(\n 647 \"--db-path\",\n 648 type=str,\n 649 default=None,\n 650 help=\"Path to SQLite database (default: data/pathways.db)\"\n 651 )\n 652\n 653 parser.add_argument(\n 654 \"--dry-run\",\n 655 action=\"store_true\",\n 656 help=\"Process data but don't insert into database\"\n 657 )\n 658\n 659 parser.add_argument(\n 660 \"--chart-type\",\n 661 type=str,\n 662 choices=[\"directory\", \"indication\", \"all\"],\n 663 default=\"directory\",\n 664 help=\"Chart type to process: 'directory' (default), 'indication', or 'all'\"\n 665 )\n 666\n 667 parser.add_argument(\n 668 \"--verbose\", \"-v\",\n 669 action=\"store_true\",\n 670 help=\"Enable verbose logging\"\n 671 )\n 672\n 673 args = parser.parse_args()\n 674\n 675 # Configure logging\n 676 import logging\n 677 log_level = logging.DEBUG if args.verbose else logging.INFO\n 678 setup_logging(level=log_level)\n 679\n 680 # Parse provider codes\n 681 provider_codes = None\n 682 if args.provider_codes:\n 683 provider_codes = [code.strip() for code in args.provider_codes.split(\",\")]\n 684\n 685 # Parse db path\n 686 db_path = Path(args.db_path) if args.db_path else None\n 687\n 688 # Run the refresh\n 689 success, message, stats = refresh_pathways(\n 690 minimum_patients=args.minimum_patients,\n 691 provider_codes=provider_codes,\n 692 db_path=db_path,\n 693 dry_run=args.dry_run,\n 694 chart_type=args.chart_type,\n 695 )\n 696\n 697 if success:\n 698 print(f\"\\n[OK] {message}\")\n 699 return 0\n 700 else:\n 701 print(f\"\\n[FAILED] {message}\", file=sys.stderr)\n 702 return 1\n 703\n 704\n 705if __name__ == \"__main__\":\n 706 sys.exit(main())\n 707\n\n\nWhenever 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.\n\n"}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"97dda50f-76e8-47b7-9db4-29886c16b3d9","tool_use_result":{"type":"text","file":{"filePath":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\cli\\refresh_pathways.py","content":"\"\"\"\nCLI command for refreshing pathway data from Snowflake.\n\nThis command fetches activity data from Snowflake, processes it through the\npathway pipeline for all 6 date filter combinations, and stores the results\nin the SQLite pathway_nodes table. Supports two chart types:\n- \"directory\": Trust  Directory  Drug  Pathway (default)\n- \"indication\": Trust  Search_Term  Drug  Pathway (requires GP diagnosis lookup)\n\nUsage:\n python -m cli.refresh_pathways\n python -m cli.refresh_pathways --minimum-patients 10\n python -m cli.refresh_pathways --provider-codes RGT,RM1\n python -m cli.refresh_pathways --chart-type all\n python -m cli.refresh_pathways --chart-type directory\n python -m cli.refresh_pathways --dry-run\n\nRun `python -m cli.refresh_pathways --help` for full options.\n\"\"\"\n\nimport argparse\nimport json\nimport sqlite3\nimport sys\nimport time\nimport uuid\nfrom datetime import datetime\nfrom pathlib import Path\nfrom typing import Optional\n\nfrom core import PathConfig, default_paths\nfrom core.logging_config import get_logger, setup_logging\nfrom data_processing.database import DatabaseManager, DatabaseConfig\nfrom data_processing.schema import (\n clear_pathway_nodes,\n get_pathway_table_counts,\n verify_pathway_tables_exist,\n create_pathway_tables,\n)\nfrom data_processing.pathway_pipeline import (\n ChartType,\n DATE_FILTER_CONFIGS,\n fetch_and_transform_data,\n process_all_date_filters,\n process_pathway_for_date_filter,\n process_indication_pathway_for_date_filter,\n extract_denormalized_fields,\n extract_indication_fields,\n convert_to_records,\n)\nfrom data_processing.diagnosis_lookup import get_patient_indication_groups\n\nlogger = get_logger(__name__)\n\n\ndef get_default_filters(paths: PathConfig) -> tuple[list[str], list[str], list[str]]:\n \"\"\"\n Load default filter values from reference files.\n\n Returns:\n Tuple of (trust_filter, drug_filter, directory_filter)\n \"\"\"\n import pandas as pd\n\n # Load default trusts\n trust_filter = []\n if paths.default_trusts_csv.exists():\n try:\n trusts_df = pd.read_csv(paths.default_trusts_csv)\n # Use the \"Name\" column which contains trust names\n if 'Name' in trusts_df.columns:\n trust_filter = trusts_df['Name'].dropna().tolist()\n else:\n # Fallback to first column if no Name column\n trust_filter = trusts_df.iloc[:, 0].dropna().tolist()\n logger.info(f\"Loaded {len(trust_filter)} default trusts\")\n except Exception as e:\n logger.warning(f\"Could not load default trusts: {e}\")\n\n # Load default drugs (Include=1 in include.csv)\n drug_filter = []\n if paths.include_csv.exists():\n try:\n drugs_df = pd.read_csv(paths.include_csv)\n if 'Include' in drugs_df.columns:\n drug_filter = drugs_df[drugs_df['Include'] == 1].iloc[:, 0].dropna().tolist()\n else:\n # Assume first column contains drug names if no Include column\n drug_filter = drugs_df.iloc[:, 0].dropna().tolist()\n logger.info(f\"Loaded {len(drug_filter)} default drugs\")\n except Exception as e:\n logger.warning(f\"Could not load default drugs: {e}\")\n\n # Load default directories\n directory_filter = []\n if paths.directory_list_csv.exists():\n try:\n dirs_df = pd.read_csv(paths.directory_list_csv)\n # Assume first column contains directory names\n directory_filter = dirs_df.iloc[:, 0].dropna().tolist()\n logger.info(f\"Loaded {len(directory_filter)} default directories\")\n except Exception as e:\n logger.warning(f\"Could not load default directories: {e}\")\n\n return trust_filter, drug_filter, directory_filter\n\n\ndef insert_pathway_records(\n conn: sqlite3.Connection,\n records: list[dict],\n) -> int:\n \"\"\"\n Insert pathway records into pathway_nodes table.\n\n Uses INSERT OR REPLACE to handle updates to existing records.\n\n Args:\n conn: SQLite connection\n records: List of record dicts from convert_to_records()\n\n Returns:\n Number of records inserted\n \"\"\"\n if not records:\n return 0\n\n # Column order matching pathway_nodes schema (includes chart_type)\n columns = [\n 'date_filter_id', 'chart_type', 'parents', 'ids', 'labels', 'level',\n 'value', 'cost', 'costpp', 'cost_pp_pa', 'colour',\n 'first_seen', 'last_seen', 'first_seen_parent', 'last_seen_parent',\n 'average_spacing', 'average_administered', 'avg_days',\n 'trust_name', 'directory', 'drug_sequence', 'data_refresh_id'\n ]\n\n placeholders = ', '.join(['?' for _ in columns])\n column_names = ', '.join(columns)\n\n insert_sql = f\"\"\"\n INSERT OR REPLACE INTO pathway_nodes ({column_names})\n VALUES ({placeholders})\n \"\"\"\n\n # Convert records to tuples in column order\n rows = []\n for record in records:\n row = tuple(record.get(col) for col in columns)\n rows.append(row)\n\n cursor = conn.executemany(insert_sql, rows)\n return cursor.rowcount\n\n\ndef log_refresh_start(\n conn: sqlite3.Connection,\n refresh_id: str,\n date_from: Optional[str] = None,\n date_to: Optional[str] = None,\n) -> None:\n \"\"\"Log the start of a refresh operation.\"\"\"\n conn.execute(\"\"\"\n INSERT INTO pathway_refresh_log\n (refresh_id, started_at, status, snowflake_query_date_from, snowflake_query_date_to)\n VALUES (?, ?, 'running', ?, ?)\n \"\"\", (refresh_id, datetime.now().isoformat(), date_from, date_to))\n conn.commit()\n\n\ndef log_refresh_complete(\n conn: sqlite3.Connection,\n refresh_id: str,\n record_count: int,\n date_filter_counts: dict[str, int],\n duration_seconds: float,\n) -> None:\n \"\"\"Log the successful completion of a refresh operation.\"\"\"\n conn.execute(\"\"\"\n UPDATE pathway_refresh_log\n SET completed_at = ?,\n status = 'completed',\n record_count = ?,\n date_filter_counts = ?,\n processing_duration_seconds = ?\n WHERE refresh_id = ?\n \"\"\", (\n datetime.now().isoformat(),\n record_count,\n json.dumps(date_filter_counts),\n duration_seconds,\n refresh_id,\n ))\n conn.commit()\n\n\ndef log_refresh_failed(\n conn: sqlite3.Connection,\n refresh_id: str,\n error_message: str,\n duration_seconds: float,\n) -> None:\n \"\"\"Log a failed refresh operation.\"\"\"\n conn.execute(\"\"\"\n UPDATE pathway_refresh_log\n SET completed_at = ?,\n status = 'failed',\n error_message = ?,\n processing_duration_seconds = ?\n WHERE refresh_id = ?\n \"\"\", (\n datetime.now().isoformat(),\n error_message,\n duration_seconds,\n refresh_id,\n ))\n conn.commit()\n\n\ndef refresh_pathways(\n minimum_patients: int = 5,\n provider_codes: Optional[list[str]] = None,\n trust_filter: Optional[list[str]] = None,\n drug_filter: Optional[list[str]] = None,\n directory_filter: Optional[list[str]] = None,\n db_path: Optional[Path] = None,\n paths: Optional[PathConfig] = None,\n dry_run: bool = False,\n chart_type: str = \"directory\",\n) -> tuple[bool, str, dict]:\n \"\"\"\n Main refresh function that orchestrates the full pipeline.\n\n Args:\n minimum_patients: Minimum patients to include a pathway\n provider_codes: List of provider codes to filter Snowflake query\n trust_filter: List of trust names to include in pathways\n drug_filter: List of drug names to include in pathways\n directory_filter: List of directories to include in pathways\n db_path: Path to SQLite database (uses default if None)\n paths: PathConfig for file paths\n dry_run: If True, don't actually insert records\n chart_type: Which chart type to process: \"directory\", \"indication\", or \"all\"\n\n Returns:\n Tuple of (success: bool, message: str, stats: dict)\n \"\"\"\n if paths is None:\n paths = default_paths\n\n # Set up database connection\n if db_path:\n db_config = DatabaseConfig(db_path=db_path)\n else:\n db_config = DatabaseConfig(data_dir=paths.data_dir)\n\n db_manager = DatabaseManager(db_config)\n\n # Load default filters if not provided\n default_trusts, default_drugs, default_dirs = get_default_filters(paths)\n\n if trust_filter is None:\n trust_filter = default_trusts\n if drug_filter is None:\n drug_filter = default_drugs\n if directory_filter is None:\n directory_filter = default_dirs\n\n # Ensure we have some filters\n if not drug_filter:\n return False, \"No drugs specified and could not load defaults\", {}\n\n # Determine which chart types to process\n if chart_type == \"all\":\n chart_types_to_process: list[ChartType] = [\"directory\", \"indication\"]\n else:\n chart_types_to_process = [chart_type] # type: ignore\n\n logger.info(\"=\" * 60)\n logger.info(\"Pathway Data Refresh Starting\")\n logger.info(\"=\" * 60)\n logger.info(f\"Minimum patients: {minimum_patients}\")\n logger.info(f\"Trust filter: {len(trust_filter)} trusts\")\n logger.info(f\"Drug filter: {len(drug_filter)} drugs\")\n logger.info(f\"Directory filter: {len(directory_filter)} directories\")\n logger.info(f\"Provider codes: {provider_codes or 'All'}\")\n logger.info(f\"Chart type(s): {', '.join(chart_types_to_process)}\")\n logger.info(f\"Database: {db_manager.db_path}\")\n logger.info(f\"Dry run: {dry_run}\")\n logger.info(\"=\" * 60)\n\n start_time = time.time()\n refresh_id = str(uuid.uuid4())[:8]\n stats = {\n \"refresh_id\": refresh_id,\n \"date_filter_counts\": {},\n \"total_records\": 0,\n \"snowflake_rows\": 0,\n }\n\n try:\n # Verify database and tables\n with db_manager.get_connection() as conn:\n missing_tables = verify_pathway_tables_exist(conn)\n if missing_tables:\n logger.info(f\"Creating missing tables: {missing_tables}\")\n create_pathway_tables(conn)\n\n # Log refresh start\n if not dry_run:\n log_refresh_start(conn, refresh_id)\n\n # Step 1: Fetch data from Snowflake\n logger.info(\"\")\n logger.info(\"Step 1/4: Fetching data from Snowflake...\")\n df = fetch_and_transform_data(\n provider_codes=provider_codes,\n paths=paths,\n )\n\n if df.empty:\n msg = \"No data returned from Snowflake\"\n logger.error(msg)\n with db_manager.get_connection() as conn:\n log_refresh_failed(conn, refresh_id, msg, time.time() - start_time)\n return False, msg, stats\n\n stats[\"snowflake_rows\"] = len(df)\n logger.info(f\"Fetched {len(df)} records from Snowflake\")\n\n # Step 2: Process all date filters for each chart type\n num_date_filters = len(DATE_FILTER_CONFIGS)\n num_chart_types = len(chart_types_to_process)\n total_datasets = num_date_filters * num_chart_types\n\n logger.info(\"\")\n logger.info(f\"Step 2/4: Processing pathway data for {total_datasets} datasets \"\n f\"({num_date_filters} date filters x {num_chart_types} chart types)...\")\n\n # Store results keyed by \"date_filter_id:chart_type\"\n results: dict[str, list[dict]] = {}\n\n for current_chart_type in chart_types_to_process:\n logger.info(\"\")\n logger.info(f\"Processing chart type: {current_chart_type}\")\n\n if current_chart_type == \"directory\":\n # Use existing process_all_date_filters for directory charts\n dir_results = process_all_date_filters(\n df=df,\n trust_filter=trust_filter,\n drug_filter=drug_filter,\n directory_filter=directory_filter,\n minimum_patients=minimum_patients,\n refresh_id=refresh_id,\n paths=paths,\n )\n # Add results with chart_type suffix\n for filter_id, records in dir_results.items():\n # Records already have chart_type set by convert_to_records\n results[f\"{filter_id}:directory\"] = records\n\n elif current_chart_type == \"indication\":\n # For indication charts, we need to look up GP diagnoses for all patients\n # using the new Snowflake-direct approach via get_patient_indication_groups()\n logger.info(\"Building indication groups from GP diagnosis lookups (Snowflake-direct)...\")\n\n # Check Snowflake availability\n from data_processing.snowflake_connector import get_connector, is_snowflake_available\n\n if not is_snowflake_available():\n logger.warning(\"Snowflake not available - cannot process indication charts\")\n for config in DATE_FILTER_CONFIGS:\n results[f\"{config.id}:indication\"] = []\n continue\n\n try:\n import pandas as pd\n connector = get_connector()\n\n # Step 1: Extract unique PseudoNHSNoLinked values from df\n # This is the patient identifier that matches PatientPseudonym in GP records\n if 'PseudoNHSNoLinked' not in df.columns:\n logger.error(\"DataFrame missing 'PseudoNHSNoLinked' column - cannot lookup GP records\")\n for config in DATE_FILTER_CONFIGS:\n results[f\"{config.id}:indication\"] = []\n continue\n\n # Get unique patient pseudonyms for GP lookup (avoid redundant queries)\n patient_pseudonyms = df['PseudoNHSNoLinked'].dropna().unique().tolist()\n\n logger.info(f\"Looking up GP diagnoses for {len(patient_pseudonyms)} unique patients...\")\n\n # Step 2: Call the new Snowflake-direct indication lookup\n gp_matches_df = get_patient_indication_groups(\n patient_pseudonyms=patient_pseudonyms,\n connector=connector,\n batch_size=500,\n )\n\n # Step 3: Build indication_df mapping UPID -> Indication_Group\n # For matched patients: Indication_Group = Search_Term\n # For unmatched patients: Indication_Group = Directory + \" (no GP dx)\"\n #\n # IMPORTANT: We need ALL unique UPIDs, not just unique PseudoNHSNoLinked.\n # A patient can have multiple UPIDs if they visited multiple providers.\n\n # Get all unique UPID records with their PseudoNHSNoLinked and Directory\n upid_lookup = df[['UPID', 'PseudoNHSNoLinked', 'Directory']].drop_duplicates(\n subset=['UPID']\n ).copy()\n\n if gp_matches_df.empty:\n logger.warning(\"No GP matches found - all patients will use fallback directory\")\n # All patients use fallback\n indication_records = []\n for _, row in upid_lookup.iterrows():\n directory = row['Directory']\n indication_records.append({\n 'UPID': row['UPID'],\n 'Indication_Group': str(directory) + \" (no GP dx)\" if pd.notna(directory) else \"UNKNOWN (no GP dx)\",\n 'Source': 'FALLBACK',\n })\n indication_df = pd.DataFrame(indication_records)\n else:\n # Create lookup dict: PseudoNHSNoLinked -> Search_Term\n match_lookup = dict(zip(\n gp_matches_df['PatientPseudonym'],\n gp_matches_df['Search_Term']\n ))\n\n # Build indication records for each unique UPID\n indication_records = []\n for _, row in upid_lookup.iterrows():\n pseudo = row['PseudoNHSNoLinked']\n upid = row['UPID']\n directory = row['Directory']\n\n if pd.notna(pseudo) and pseudo in match_lookup:\n indication_records.append({\n 'UPID': upid,\n 'Indication_Group': match_lookup[pseudo],\n 'Source': 'DIAGNOSIS',\n })\n else:\n # Use fallback: Directory + \" (no GP dx)\"\n fallback_label = str(directory) + \" (no GP dx)\" if pd.notna(directory) else \"UNKNOWN (no GP dx)\"\n indication_records.append({\n 'UPID': upid,\n 'Indication_Group': fallback_label,\n 'Source': 'FALLBACK',\n })\n\n indication_df = pd.DataFrame(indication_records)\n\n # Log coverage statistics\n if not indication_df.empty:\n diagnosis_count = (indication_df['Source'] == 'DIAGNOSIS').sum()\n fallback_count = (indication_df['Source'] == 'FALLBACK').sum()\n total = len(indication_df)\n stats[\"diagnosis_coverage\"] = {\n \"diagnosis\": int(diagnosis_count),\n \"fallback\": int(fallback_count),\n \"total\": total,\n \"diagnosis_pct\": round(100 * diagnosis_count / total, 1) if total > 0 else 0,\n }\n logger.info(f\"Indication coverage: {diagnosis_count}/{total} ({stats['diagnosis_coverage']['diagnosis_pct']}%) diagnosis-matched\")\n\n # Log top indication groups\n top_indications = indication_df[indication_df['Source'] == 'DIAGNOSIS']['Indication_Group'].value_counts().head(5)\n if len(top_indications) > 0:\n logger.info(f\"Top 5 indications: {dict(top_indications)}\")\n\n # Rename column for compatibility with generate_icicle_chart_indication\n # It expects indication_df to have 'Directory' column (mapped from Indication_Group)\n indication_df_for_chart = indication_df[['UPID', 'Indication_Group']].copy()\n indication_df_for_chart = indication_df_for_chart.rename(columns={'Indication_Group': 'Directory'})\n # Ensure unique UPID index (build_hierarchy requires uniquely valued Index)\n # Keep first occurrence - DIAGNOSIS entries should come before FALLBACK\n indication_df_for_chart = indication_df_for_chart.drop_duplicates(subset=['UPID'], keep='first')\n indication_df_for_chart = indication_df_for_chart.set_index('UPID')\n\n # Process each date filter with indication grouping\n for config in DATE_FILTER_CONFIGS:\n logger.info(f\"Processing indication pathway for {config.id}\")\n\n ice_df = process_indication_pathway_for_date_filter(\n df=df,\n indication_df=indication_df_for_chart,\n config=config,\n trust_filter=trust_filter,\n drug_filter=drug_filter,\n directory_filter=directory_filter,\n minimum_patients=minimum_patients,\n paths=paths,\n )\n\n if ice_df is None:\n logger.warning(f\"No indication pathway data for {config.id}\")\n results[f\"{config.id}:indication\"] = []\n continue\n\n # Extract denormalized fields (using indication variant)\n ice_df = extract_indication_fields(ice_df)\n\n # Convert to records with chart_type=\"indication\"\n records = convert_to_records(ice_df, config.id, refresh_id, chart_type=\"indication\")\n results[f\"{config.id}:indication\"] = records\n\n logger.info(f\"Completed {config.id}:indication: {len(records)} nodes\")\n else:\n logger.warning(\"Empty indication_df - skipping indication charts\")\n for config in DATE_FILTER_CONFIGS:\n results[f\"{config.id}:indication\"] = []\n\n except Exception as e:\n logger.error(f\"Error processing indication charts: {e}\")\n logger.exception(e)\n for config in DATE_FILTER_CONFIGS:\n results[f\"{config.id}:indication\"] = []\n\n # Count records per filter and chart type\n stats[\"chart_type_counts\"] = {}\n for key, records in results.items():\n stats[\"date_filter_counts\"][key] = len(records)\n stats[\"total_records\"] += len(records)\n # Also track by chart type\n _, ct = key.split(\":\")\n stats[\"chart_type_counts\"][ct] = stats[\"chart_type_counts\"].get(ct, 0) + len(records)\n\n logger.info(\"\")\n logger.info(f\"Processed {stats['total_records']} total pathway nodes\")\n for chart_type_name, count in stats.get(\"chart_type_counts\", {}).items():\n logger.info(f\" {chart_type_name}: {count} nodes total\")\n for key, count in sorted(stats[\"date_filter_counts\"].items()):\n if count > 0:\n logger.info(f\" {key}: {count} nodes\")\n\n if dry_run:\n logger.info(\"\")\n logger.info(\"DRY RUN - Skipping database insertion\")\n elapsed = time.time() - start_time\n return True, f\"Dry run complete: {stats['total_records']} records would be inserted\", stats\n\n # Step 3: Clear existing data and insert new records\n logger.info(\"\")\n logger.info(\"Step 3/4: Clearing existing pathway data and inserting new records...\")\n\n with db_manager.get_transaction() as conn:\n # Clear all existing pathway nodes\n deleted = clear_pathway_nodes(conn)\n logger.info(f\"Cleared {deleted} existing pathway nodes\")\n\n # Insert new records for each date filter + chart type combination\n total_inserted = 0\n for key, records in results.items():\n if records:\n inserted = insert_pathway_records(conn, records)\n total_inserted += len(records)\n logger.info(f\" Inserted {len(records)} records for {key}\")\n\n # Step 4: Log completion\n logger.info(\"\")\n logger.info(\"Step 4/4: Logging refresh completion...\")\n\n elapsed = time.time() - start_time\n\n with db_manager.get_connection() as conn:\n log_refresh_complete(\n conn=conn,\n refresh_id=refresh_id,\n record_count=stats[\"total_records\"],\n date_filter_counts=stats[\"date_filter_counts\"],\n duration_seconds=elapsed,\n )\n\n # Verify final counts\n counts = get_pathway_table_counts(conn)\n logger.info(f\"Final table counts: {counts}\")\n\n logger.info(\"\")\n logger.info(\"=\" * 60)\n logger.info(f\"Refresh completed successfully in {elapsed:.1f} seconds\")\n logger.info(f\"Total records: {stats['total_records']}\")\n logger.info(f\"Refresh ID: {refresh_id}\")\n logger.info(\"=\" * 60)\n\n return True, f\"Refresh complete: {stats['total_records']} records in {elapsed:.1f}s\", stats\n\n except Exception as e:\n elapsed = time.time() - start_time\n error_msg = f\"Refresh failed: {e}\"\n logger.error(error_msg, exc_info=True)\n\n try:\n with db_manager.get_connection() as conn:\n log_refresh_failed(conn, refresh_id, str(e), elapsed)\n except Exception:\n pass # Don't fail the error handling\n\n return False, error_msg, stats\n\n\ndef main() -> int:\n \"\"\"CLI entry point.\"\"\"\n parser = argparse.ArgumentParser(\n description=\"Refresh pathway data from Snowflake\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"\nExamples:\n # Basic refresh with defaults (directory chart only)\n python -m cli.refresh_pathways\n\n # Refresh both chart types (directory and indication)\n python -m cli.refresh_pathways --chart-type all\n\n # Refresh only indication-based charts\n python -m cli.refresh_pathways --chart-type indication\n\n # Refresh with custom minimum patients\n python -m cli.refresh_pathways --minimum-patients 10\n\n # Refresh specific providers only\n python -m cli.refresh_pathways --provider-codes RGT,RM1\n\n # Dry run to see what would be processed\n python -m cli.refresh_pathways --dry-run\n\n # Verbose output\n python -m cli.refresh_pathways --verbose\n \"\"\"\n )\n\n parser.add_argument(\n \"--minimum-patients\",\n type=int,\n default=5,\n help=\"Minimum patients to include a pathway (default: 5)\"\n )\n\n parser.add_argument(\n \"--provider-codes\",\n type=str,\n default=None,\n help=\"Comma-separated list of provider codes to filter (default: all)\"\n )\n\n parser.add_argument(\n \"--db-path\",\n type=str,\n default=None,\n help=\"Path to SQLite database (default: data/pathways.db)\"\n )\n\n parser.add_argument(\n \"--dry-run\",\n action=\"store_true\",\n help=\"Process data but don't insert into database\"\n )\n\n parser.add_argument(\n \"--chart-type\",\n type=str,\n choices=[\"directory\", \"indication\", \"all\"],\n default=\"directory\",\n help=\"Chart type to process: 'directory' (default), 'indication', or 'all'\"\n )\n\n parser.add_argument(\n \"--verbose\", \"-v\",\n action=\"store_true\",\n help=\"Enable verbose logging\"\n )\n\n args = parser.parse_args()\n\n # Configure logging\n import logging\n log_level = logging.DEBUG if args.verbose else logging.INFO\n setup_logging(level=log_level)\n\n # Parse provider codes\n provider_codes = None\n if args.provider_codes:\n provider_codes = [code.strip() for code in args.provider_codes.split(\",\")]\n\n # Parse db path\n db_path = Path(args.db_path) if args.db_path else None\n\n # Run the refresh\n success, message, stats = refresh_pathways(\n minimum_patients=args.minimum_patients,\n provider_codes=provider_codes,\n db_path=db_path,\n dry_run=args.dry_run,\n chart_type=args.chart_type,\n )\n\n if success:\n print(f\"\\n[OK] {message}\")\n return 0\n else:\n print(f\"\\n[FAILED] {message}\", file=sys.stderr)\n return 1\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","numLines":707,"startLine":1,"totalLines":707}}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01SPtt3ThiBTCY77ANd815S5","type":"message","role":"assistant","content":[{"type":"text","text":"Now I have the full picture. I can see the critical issue in `refresh_pathways.py` lines 424-428 ÔÇö `dict(zip(...))` which only keeps the LAST match per patient (since the new query returns multiple rows per patient). This will be fixed in Task 3.1.\n\nNow I'm ready to build Task 2.1: `assign_drug_indications()`. Let me mark it in-progress and start implementing."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":9879,"cache_read_input_tokens":107086,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":9879},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"b6e01980-bf82-407e-a081-407f533bef54"}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01SPtt3ThiBTCY77ANd815S5","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01Tvxan4PLS5bb3jjqPQPpwQ","name":"TodoWrite","input":{"todos":[{"content":"Read project files (progress.txt, IMPLEMENTATION_PLAN.md, guardrails.md)","status":"completed","activeForm":"Reading project files"},{"content":"Build assign_drug_indications() function (Task 2.1 + 2.2)","status":"in_progress","activeForm":"Building assign_drug_indications() function"},{"content":"Validate code (py_compile, import check, mock data test)","status":"pending","activeForm":"Validating code"},{"content":"Commit and update progress.txt","status":"pending","activeForm":"Committing and updating progress"}]}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":9879,"cache_read_input_tokens":107086,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":9879},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"85172ba8-1530-4707-a2f6-423891f06a4b"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01Tvxan4PLS5bb3jjqPQPpwQ","type":"tool_result","content":"Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable"}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"b3855b0b-b9b7-485d-b067-af82b023f2e8","tool_use_result":{"oldTodos":[],"newTodos":[{"content":"Read project files (progress.txt, IMPLEMENTATION_PLAN.md, guardrails.md)","status":"completed","activeForm":"Reading project files"},{"content":"Build assign_drug_indications() function (Task 2.1 + 2.2)","status":"in_progress","activeForm":"Building assign_drug_indications() function"},{"content":"Validate code (py_compile, import check, mock data test)","status":"pending","activeForm":"Validating code"},{"content":"Commit and update progress.txt","status":"pending","activeForm":"Committing and updating progress"}]}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_016fakBqsAyPbU7bQnVJ3sqL","type":"message","role":"assistant","content":[{"type":"text","text":"Now implementing the `assign_drug_indications()` function. The key logic:\n\n1. For each UPID + Drug Name pair in the HCD data:\n - Look up patient's GP-matched Search_Terms (from gp_matches_df via PseudoNHSNoLinked)\n - Look up which Search_Terms list this drug (from drug mapping)\n - Intersect  valid indications\n - Pick highest code_frequency as tiebreaker (or alphabetical if tied)\n - Modify UPID: `{UPID}|{search_term}` or fallback `{UPID}|{Directory} (no GP dx)`\n\n2. Build indication_df mapping modified UPID  Search_Term\n\nI'll add this function to `diagnosis_lookup.py` since that's where all the related functions live."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":354,"cache_read_input_tokens":116965,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":354},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"135bcce8-94d3-4364-a08d-accbdb1b543f"}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_016fakBqsAyPbU7bQnVJ3sqL","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_0178KQTzfJyHJHykaxL7Tsg5","name":"Read","input":{"file_path":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\data_processing\\diagnosis_lookup.py","offset":1090,"limit":50}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":354,"cache_read_input_tokens":116965,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":354},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"26e2507e-9b60-471e-abc2-39bd5e100936"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_0178KQTzfJyHJHykaxL7Tsg5","type":"tool_result","content":" 1090# === Drug-to-indication mapping from DimSearchTerm.csv ===\n 1091\n 1092\n 1093# Merge related Search_Terms into canonical names.\n 1094# Asthma variants are clinically the same condition at different severity levels.\n 1095# Urticaria is a separate condition  do NOT merge with asthma.\n 1096SEARCH_TERM_MERGE_MAP: dict[str, str] = {\n 1097 \"allergic asthma\": \"asthma\",\n 1098 \"severe persistent allergic asthma\": \"asthma\",\n 1099}\n 1100\n 1101\n 1102def load_drug_indication_mapping(\n 1103 csv_path: Optional[str] = None,\n 1104) -> tuple[dict[str, list[str]], dict[str, list[str]]]:\n 1105 \"\"\"\n 1106 Load the drug-to-Search_Term mapping from DimSearchTerm.csv.\n 1107\n 1108 Builds two lookup dicts:\n 1109 - fragment_to_search_terms: drug fragment (UPPERCASE) -> list of Search_Terms containing it\n 1110 - search_term_to_fragments: search_term -> list of drug fragments (UPPERCASE)\n 1111\n 1112 DimSearchTerm.csv has columns: Search_Term, CleanedDrugName, PrimaryDirectorate\n 1113 CleanedDrugName is pipe-separated (e.g., \"ADALIMUMAB|GOLIMUMAB|IXEKIZUMAB\").\n 1114\n 1115 Note: A Search_Term can appear multiple times with different PrimaryDirectorates\n 1116 (e.g., \"diabetes\" appears under both DIABETIC MEDICINE and OPHTHALMOLOGY).\n 1117 Drug fragments from all rows for the same Search_Term are combined.\n 1118\n 1119 Asthma-related Search_Terms (\"allergic asthma\", \"severe persistent allergic asthma\")\n 1120 are merged into \"asthma\" to match the CLUSTER_MAPPING_SQL normalization.\n 1121 \"urticaria\" stays separate.\n 1122\n 1123 Args:\n 1124 csv_path: Path to DimSearchTerm.csv. Defaults to data/DimSearchTerm.csv.\n 1125\n 1126 Returns:\n 1127 Tuple of (fragment_to_search_terms, search_term_to_fragments)\n 1128 \"\"\"\n 1129 if csv_path is None:\n 1130 csv_path = str(Path(__file__).parent.parent / \"data\" / \"DimSearchTerm.csv\")\n 1131\n 1132 fragment_to_search_terms: dict[str, list[str]] = {}\n 1133 search_term_to_fragments: dict[str, list[str]] = {}\n 1134\n 1135 try:\n 1136 with open(csv_path, \"r\", encoding=\"utf-8\") as f:\n 1137 reader = csv.DictReader(f)\n 1138 for row in reader:\n 1139 search_term = row.get(\"Search_Term\", \"\").strip()\n\n\nWhenever 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.\n\n"}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"2101dcfa-c9cf-4039-adf1-80c15606767f","tool_use_result":{"type":"text","file":{"filePath":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\data_processing\\diagnosis_lookup.py","content":"# === Drug-to-indication mapping from DimSearchTerm.csv ===\n\n\n# Merge related Search_Terms into canonical names.\n# Asthma variants are clinically the same condition at different severity levels.\n# Urticaria is a separate condition  do NOT merge with asthma.\nSEARCH_TERM_MERGE_MAP: dict[str, str] = {\n \"allergic asthma\": \"asthma\",\n \"severe persistent allergic asthma\": \"asthma\",\n}\n\n\ndef load_drug_indication_mapping(\n csv_path: Optional[str] = None,\n) -> tuple[dict[str, list[str]], dict[str, list[str]]]:\n \"\"\"\n Load the drug-to-Search_Term mapping from DimSearchTerm.csv.\n\n Builds two lookup dicts:\n - fragment_to_search_terms: drug fragment (UPPERCASE) -> list of Search_Terms containing it\n - search_term_to_fragments: search_term -> list of drug fragments (UPPERCASE)\n\n DimSearchTerm.csv has columns: Search_Term, CleanedDrugName, PrimaryDirectorate\n CleanedDrugName is pipe-separated (e.g., \"ADALIMUMAB|GOLIMUMAB|IXEKIZUMAB\").\n\n Note: A Search_Term can appear multiple times with different PrimaryDirectorates\n (e.g., \"diabetes\" appears under both DIABETIC MEDICINE and OPHTHALMOLOGY).\n Drug fragments from all rows for the same Search_Term are combined.\n\n Asthma-related Search_Terms (\"allergic asthma\", \"severe persistent allergic asthma\")\n are merged into \"asthma\" to match the CLUSTER_MAPPING_SQL normalization.\n \"urticaria\" stays separate.\n\n Args:\n csv_path: Path to DimSearchTerm.csv. Defaults to data/DimSearchTerm.csv.\n\n Returns:\n Tuple of (fragment_to_search_terms, search_term_to_fragments)\n \"\"\"\n if csv_path is None:\n csv_path = str(Path(__file__).parent.parent / \"data\" / \"DimSearchTerm.csv\")\n\n fragment_to_search_terms: dict[str, list[str]] = {}\n search_term_to_fragments: dict[str, list[str]] = {}\n\n try:\n with open(csv_path, \"r\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n for row in reader:\n search_term = row.get(\"Search_Term\", \"\").strip()","numLines":50,"startLine":1090,"totalLines":1574}}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_011qD5mM6NtHkXkRkCqMvMJj","type":"message","role":"assistant","content":[{"type":"text","text":"Now I'll add the `assign_drug_indications()` function. I'll insert it after `get_search_terms_for_drug()` (line 1204) and before the `CLUSTER_MAPPING_SQL` section (line 1207)."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":1251,"cache_read_input_tokens":117319,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":1251},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"a7751ce2-c8d0-4c9f-9803-930a7b142b4d"}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_011qD5mM6NtHkXkRkCqMvMJj","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_019G9MeAokjyqZgA1REbfsS4","name":"Edit","input":{"replace_all":false,"file_path":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\data_processing\\diagnosis_lookup.py","old_string":" return matched_terms\n\n\n# === NEW APPROACH: Query Snowflake directly using cluster CTE ===","new_string":" return matched_terms\n\n\ndef assign_drug_indications(\n df: \"pd.DataFrame\",\n gp_matches_df: \"pd.DataFrame\",\n search_term_to_fragments: dict[str, list[str]],\n) -> \"tuple[pd.DataFrame, pd.DataFrame]\":\n \"\"\"\n Assign drug-aware indications by cross-referencing GP diagnoses with drug mappings.\n\n For each UPID + Drug Name pair in the HCD data:\n 1. Look up patient's GP-matched Search_Terms (via PseudoNHSNoLinked  gp_matches_df)\n 2. Look up which Search_Terms list this drug (via search_term_to_fragments)\n 3. Intersect = valid indications for this drug-patient pair\n 4. If 1 match: use it\n 5. If multiple: pick highest code_frequency (most GP coding = most likely indication)\n 6. If tied frequency: alphabetical Search_Term for determinism\n 7. If 0 matches: fallback to \"{Directory} (no GP dx)\"\n\n Modifies UPID to include indication: \"{UPID}|{search_term}\" or \"{UPID}|{Directory} (no GP dx)\".\n This makes drugs under different indications appear as separate pathways.\n\n Args:\n df: HCD DataFrame with columns: UPID, Drug Name, PseudoNHSNoLinked, Directory\n gp_matches_df: GP matches from get_patient_indication_groups() with columns:\n PatientPseudonym, Search_Term, code_frequency\n (multiple rows per patient, one per matched Search_Term)\n search_term_to_fragments: From load_drug_indication_mapping()[1].\n Maps search_term -> list of drug fragments (UPPERCASE).\n\n Returns:\n Tuple of (modified_df, indication_df):\n - modified_df: Copy of df with UPID replaced by \"{UPID}|{indication}\"\n - indication_df: DataFrame indexed by modified UPID with 'Directory' column\n containing the Search_Term (or fallback label) for pathway hierarchy\n \"\"\"\n import pandas as pd\n\n modified_df = df.copy()\n\n # Build GP match lookup: PseudoNHSNoLinked -> {Search_Term: code_frequency}\n gp_lookup: dict[str, dict[str, int]] = {}\n if not gp_matches_df.empty:\n for _, row in gp_matches_df.iterrows():\n pseudo = row['PatientPseudonym']\n term = row['Search_Term']\n freq = int(row.get('code_frequency', 0))\n if pseudo not in gp_lookup:\n gp_lookup[pseudo] = {}\n gp_lookup[pseudo][term] = freq\n\n logger.info(f\"GP lookup built: {len(gp_lookup)} patients with GP matches\")\n\n # Cache drug -> Search_Terms lookups to avoid recomputing per row\n drug_search_terms_cache: dict[str, list[str]] = {}\n\n def get_drug_terms(drug_name: str) -> list[str]:\n if drug_name not in drug_search_terms_cache:\n drug_search_terms_cache[drug_name] = get_search_terms_for_drug(\n drug_name, search_term_to_fragments\n )\n return drug_search_terms_cache[drug_name]\n\n # Process each row: determine indication for each UPID + Drug Name\n # We work at the (UPID, Drug Name) pair level, then apply to all rows\n # Key: (UPID, Drug Name) -> (matched_search_term_or_fallback, is_diagnosis)\n pair_indication_cache: dict[tuple[str, str], tuple[str, bool]] = {}\n\n # Get unique (UPID, Drug Name, PseudoNHSNoLinked, Directory) combos\n required_cols = ['UPID', 'Drug Name', 'PseudoNHSNoLinked', 'Directory']\n unique_pairs = modified_df[required_cols].drop_duplicates(\n subset=['UPID', 'Drug Name']\n )\n\n match_count = 0\n fallback_count = 0\n tiebreak_count = 0\n\n for _, pair_row in unique_pairs.iterrows():\n upid = pair_row['UPID']\n drug_name = pair_row['Drug Name']\n pseudo = pair_row['PseudoNHSNoLinked']\n directory = pair_row['Directory']\n\n # Get Search_Terms this drug maps to\n drug_terms = get_drug_terms(drug_name)\n\n # Get patient's GP-matched Search_Terms\n patient_gp_terms = gp_lookup.get(pseudo, {}) if pd.notna(pseudo) else {}\n\n # Intersect: Search_Terms that list this drug AND patient has GP dx for\n valid_indications = {\n term: patient_gp_terms[term]\n for term in drug_terms\n if term in patient_gp_terms\n }\n\n if len(valid_indications) == 1:\n matched_term = next(iter(valid_indications))\n pair_indication_cache[(upid, drug_name)] = (matched_term, True)\n match_count += 1\n\n elif len(valid_indications) > 1:\n # Tiebreaker: highest code_frequency, then alphabetical\n sorted_terms = sorted(\n valid_indications.items(),\n key=lambda x: (-x[1], x[0]),\n )\n matched_term = sorted_terms[0][0]\n pair_indication_cache[(upid, drug_name)] = (matched_term, True)\n match_count += 1\n tiebreak_count += 1\n\n else:\n # No intersection: fallback to directory\n if pd.notna(directory):\n fallback_label = f\"{directory} (no GP dx)\"\n else:\n fallback_label = \"UNKNOWN (no GP dx)\"\n pair_indication_cache[(upid, drug_name)] = (fallback_label, False)\n fallback_count += 1\n\n total_pairs = len(unique_pairs)\n logger.info(f\"Drug-indication matching complete:\")\n logger.info(f\" Total UPID-Drug pairs: {total_pairs}\")\n logger.info(f\" Matched (GP dx + drug mapping): {match_count} ({100*match_count/total_pairs:.1f}%)\" if total_pairs > 0 else f\" Matched: 0\")\n logger.info(f\" Tiebreaker used: {tiebreak_count}\")\n logger.info(f\" Fallback (no match): {fallback_count} ({100*fallback_count/total_pairs:.1f}%)\" if total_pairs > 0 else f\" Fallback: 0\")\n\n # Apply modified UPIDs to all rows\n # Build vectorized lookup: original UPID + Drug Name -> modified UPID\n def build_modified_upid(row: \"pd.Series\") -> str:\n upid = row['UPID']\n drug_name = row['Drug Name']\n key = (upid, drug_name)\n if key in pair_indication_cache:\n indication, _ = pair_indication_cache[key]\n return f\"{upid}|{indication}\"\n # Shouldn't happen, but fallback\n return f\"{upid}|UNKNOWN (no GP dx)\"\n\n modified_df['UPID'] = modified_df.apply(build_modified_upid, axis=1)\n\n # Build indication_df: modified UPID -> Search_Term/fallback label\n # This maps each unique modified UPID to its indication for the pathway hierarchy\n indication_records: list[dict[str, str]] = []\n seen_upids: set[str] = set()\n\n for (original_upid, drug_name), (indication, is_diagnosis) in pair_indication_cache.items():\n modified_upid = f\"{original_upid}|{indication}\"\n if modified_upid not in seen_upids:\n indication_records.append({\n 'UPID': modified_upid,\n 'Directory': indication,\n })\n seen_upids.add(modified_upid)\n\n indication_df = pd.DataFrame(indication_records)\n if not indication_df.empty:\n indication_df = indication_df.set_index('UPID')\n\n logger.info(f\" Unique modified UPIDs: {len(indication_df)}\")\n\n # Log top indications\n if not indication_df.empty:\n top_terms = indication_df['Directory'].value_counts().head(5)\n logger.info(f\" Top 5 indications: {dict(top_terms)}\")\n\n return modified_df, indication_df\n\n\n# === NEW APPROACH: Query Snowflake directly using cluster CTE ==="}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":1251,"cache_read_input_tokens":117319,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":1251},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"d2363220-a815-458d-a73e-7bc439603b23"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_019G9MeAokjyqZgA1REbfsS4","type":"tool_result","content":"The file C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\data_processing\\diagnosis_lookup.py has been updated successfully."}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"83befc2a-34db-46a9-85f9-51c36c1276c5","tool_use_result":{"filePath":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\data_processing\\diagnosis_lookup.py","oldString":" return matched_terms\n\n\n# === NEW APPROACH: Query Snowflake directly using cluster CTE ===","newString":" return matched_terms\n\n\ndef assign_drug_indications(\n df: \"pd.DataFrame\",\n gp_matches_df: \"pd.DataFrame\",\n search_term_to_fragments: dict[str, list[str]],\n) -> \"tuple[pd.DataFrame, pd.DataFrame]\":\n \"\"\"\n Assign drug-aware indications by cross-referencing GP diagnoses with drug mappings.\n\n For each UPID + Drug Name pair in the HCD data:\n 1. Look up patient's GP-matched Search_Terms (via PseudoNHSNoLinked  gp_matches_df)\n 2. Look up which Search_Terms list this drug (via search_term_to_fragments)\n 3. Intersect = valid indications for this drug-patient pair\n 4. If 1 match: use it\n 5. If multiple: pick highest code_frequency (most GP coding = most likely indication)\n 6. If tied frequency: alphabetical Search_Term for determinism\n 7. If 0 matches: fallback to \"{Directory} (no GP dx)\"\n\n Modifies UPID to include indication: \"{UPID}|{search_term}\" or \"{UPID}|{Directory} (no GP dx)\".\n This makes drugs under different indications appear as separate pathways.\n\n Args:\n df: HCD DataFrame with columns: UPID, Drug Name, PseudoNHSNoLinked, Directory\n gp_matches_df: GP matches from get_patient_indication_groups() with columns:\n PatientPseudonym, Search_Term, code_frequency\n (multiple rows per patient, one per matched Search_Term)\n search_term_to_fragments: From load_drug_indication_mapping()[1].\n Maps search_term -> list of drug fragments (UPPERCASE).\n\n Returns:\n Tuple of (modified_df, indication_df):\n - modified_df: Copy of df with UPID replaced by \"{UPID}|{indication}\"\n - indication_df: DataFrame indexed by modified UPID with 'Directory' column\n containing the Search_Term (or fallback label) for pathway hierarchy\n \"\"\"\n import pandas as pd\n\n modified_df = df.copy()\n\n # Build GP match lookup: PseudoNHSNoLinked -> {Search_Term: code_frequency}\n gp_lookup: dict[str, dict[str, int]] = {}\n if not gp_matches_df.empty:\n for _, row in gp_matches_df.iterrows():\n pseudo = row['PatientPseudonym']\n term = row['Search_Term']\n freq = int(row.get('code_frequency', 0))\n if pseudo not in gp_lookup:\n gp_lookup[pseudo] = {}\n gp_lookup[pseudo][term] = freq\n\n logger.info(f\"GP lookup built: {len(gp_lookup)} patients with GP matches\")\n\n # Cache drug -> Search_Terms lookups to avoid recomputing per row\n drug_search_terms_cache: dict[str, list[str]] = {}\n\n def get_drug_terms(drug_name: str) -> list[str]:\n if drug_name not in drug_search_terms_cache:\n drug_search_terms_cache[drug_name] = get_search_terms_for_drug(\n drug_name, search_term_to_fragments\n )\n return drug_search_terms_cache[drug_name]\n\n # Process each row: determine indication for each UPID + Drug Name\n # We work at the (UPID, Drug Name) pair level, then apply to all rows\n # Key: (UPID, Drug Name) -> (matched_search_term_or_fallback, is_diagnosis)\n pair_indication_cache: dict[tuple[str, str], tuple[str, bool]] = {}\n\n # Get unique (UPID, Drug Name, PseudoNHSNoLinked, Directory) combos\n required_cols = ['UPID', 'Drug Name', 'PseudoNHSNoLinked', 'Directory']\n unique_pairs = modified_df[required_cols].drop_duplicates(\n subset=['UPID', 'Drug Name']\n )\n\n match_count = 0\n fallback_count = 0\n tiebreak_count = 0\n\n for _, pair_row in unique_pairs.iterrows():\n upid = pair_row['UPID']\n drug_name = pair_row['Drug Name']\n pseudo = pair_row['PseudoNHSNoLinked']\n directory = pair_row['Directory']\n\n # Get Search_Terms this drug maps to\n drug_terms = get_drug_terms(drug_name)\n\n # Get patient's GP-matched Search_Terms\n patient_gp_terms = gp_lookup.get(pseudo, {}) if pd.notna(pseudo) else {}\n\n # Intersect: Search_Terms that list this drug AND patient has GP dx for\n valid_indications = {\n term: patient_gp_terms[term]\n for term in drug_terms\n if term in patient_gp_terms\n }\n\n if len(valid_indications) == 1:\n matched_term = next(iter(valid_indications))\n pair_indication_cache[(upid, drug_name)] = (matched_term, True)\n match_count += 1\n\n elif len(valid_indications) > 1:\n # Tiebreaker: highest code_frequency, then alphabetical\n sorted_terms = sorted(\n valid_indications.items(),\n key=lambda x: (-x[1], x[0]),\n )\n matched_term = sorted_terms[0][0]\n pair_indication_cache[(upid, drug_name)] = (matched_term, True)\n match_count += 1\n tiebreak_count += 1\n\n else:\n # No intersection: fallback to directory\n if pd.notna(directory):\n fallback_label = f\"{directory} (no GP dx)\"\n else:\n fallback_label = \"UNKNOWN (no GP dx)\"\n pair_indication_cache[(upid, drug_name)] = (fallback_label, False)\n fallback_count += 1\n\n total_pairs = len(unique_pairs)\n logger.info(f\"Drug-indication matching complete:\")\n logger.info(f\" Total UPID-Drug pairs: {total_pairs}\")\n logger.info(f\" Matched (GP dx + drug mapping): {match_count} ({100*match_count/total_pairs:.1f}%)\" if total_pairs > 0 else f\" Matched: 0\")\n logger.info(f\" Tiebreaker used: {tiebreak_count}\")\n logger.info(f\" Fallback (no match): {fallback_count} ({100*fallback_count/total_pairs:.1f}%)\" if total_pairs > 0 else f\" Fallback: 0\")\n\n # Apply modified UPIDs to all rows\n # Build vectorized lookup: original UPID + Drug Name -> modified UPID\n def build_modified_upid(row: \"pd.Series\") -> str:\n upid = row['UPID']\n drug_name = row['Drug Name']\n key = (upid, drug_name)\n if key in pair_indication_cache:\n indication, _ = pair_indication_cache[key]\n return f\"{upid}|{indication}\"\n # Shouldn't happen, but fallback\n return f\"{upid}|UNKNOWN (no GP dx)\"\n\n modified_df['UPID'] = modified_df.apply(build_modified_upid, axis=1)\n\n # Build indication_df: modified UPID -> Search_Term/fallback label\n # This maps each unique modified UPID to its indication for the pathway hierarchy\n indication_records: list[dict[str, str]] = []\n seen_upids: set[str] = set()\n\n for (original_upid, drug_name), (indication, is_diagnosis) in pair_indication_cache.items():\n modified_upid = f\"{original_upid}|{indication}\"\n if modified_upid not in seen_upids:\n indication_records.append({\n 'UPID': modified_upid,\n 'Directory': indication,\n })\n seen_upids.add(modified_upid)\n\n indication_df = pd.DataFrame(indication_records)\n if not indication_df.empty:\n indication_df = indication_df.set_index('UPID')\n\n logger.info(f\" Unique modified UPIDs: {len(indication_df)}\")\n\n # Log top indications\n if not indication_df.empty:\n top_terms = indication_df['Directory'].value_counts().head(5)\n logger.info(f\" Top 5 indications: {dict(top_terms)}\")\n\n return modified_df, indication_df\n\n\n# === NEW APPROACH: Query Snowflake directly using cluster CTE ===","originalFile":"\"\"\"\nDiagnosis lookup module for NHS Patient Pathway Analysis.\n\nProvides functions to validate patient indications by checking GP diagnosis records\nagainst SNOMED cluster codes. Uses the drug-to-cluster mapping from\ndrug_indication_clusters.csv and queries Snowflake for SNOMED codes and GP records.\n\nKey workflow:\n1. Get drug's valid indication clusters from local mapping\n2. Get all SNOMED codes for those clusters from Snowflake\n3. Check if patient has any of those SNOMED codes in GP records\n4. Report indication validation status\n\nIMPORTANT: HCD activity data indication codes are UNRELIABLE. This module uses\nGP/Primary Care data (PrimaryCareClinicalCoding) as the authoritative source.\n\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom datetime import date, datetime\nfrom pathlib import Path\nfrom typing import Optional, Callable, Any, cast, TYPE_CHECKING\nimport csv\n\nif TYPE_CHECKING:\n import pandas as pd\n\nfrom core.logging_config import get_logger\nfrom data_processing.database import DatabaseManager, default_db_manager\nfrom data_processing.snowflake_connector import (\n SnowflakeConnector,\n get_connector,\n is_snowflake_available,\n is_snowflake_configured,\n SNOWFLAKE_AVAILABLE,\n)\nfrom data_processing.cache import get_cache, is_cache_enabled\n\nlogger = get_logger(__name__)\n\n\n@dataclass\nclass ClusterSnomedCodes:\n \"\"\"SNOMED codes for a clinical coding cluster.\"\"\"\n cluster_id: str\n cluster_description: str\n snomed_codes: list[str] = field(default_factory=list)\n snomed_descriptions: dict[str, str] = field(default_factory=dict)\n\n @property\n def code_count(self) -> int:\n return len(self.snomed_codes)\n\n\n@dataclass\nclass IndicationValidationResult:\n \"\"\"Result of validating a patient's indication for a drug.\"\"\"\n patient_pseudonym: str\n drug_name: str\n has_valid_indication: bool\n matched_cluster_id: Optional[str] = None\n matched_snomed_code: Optional[str] = None\n matched_snomed_description: Optional[str] = None\n checked_clusters: list[str] = field(default_factory=list)\n total_codes_checked: int = 0\n source: str = \"GP_SNOMED\" # GP_SNOMED | NONE\n error_message: Optional[str] = None\n\n\n@dataclass\nclass DrugIndicationMatchRate:\n \"\"\"Match rate statistics for a drug's indication validation.\"\"\"\n drug_name: str\n total_patients: int\n patients_with_indication: int\n patients_without_indication: int\n match_rate: float # 0.0 to 1.0\n clusters_checked: list[str] = field(default_factory=list)\n sample_unmatched: list[str] = field(default_factory=list) # Sample patient IDs\n\n\n@dataclass\nclass DrugSnomedMapping:\n \"\"\"SNOMED code mapping for a drug from ref_drug_snomed_mapping.\"\"\"\n snomed_code: str\n snomed_description: str\n search_term: str\n primary_directorate: str\n indication: str = \"\"\n ta_id: str = \"\"\n\n\n@dataclass\nclass DirectSnomedMatchResult:\n \"\"\"Result of direct SNOMED code lookup in GP records.\"\"\"\n patient_pseudonym: str\n matched: bool\n snomed_code: Optional[str] = None\n snomed_description: Optional[str] = None\n search_term: Optional[str] = None\n primary_directorate: Optional[str] = None\n event_date: Optional[datetime] = None\n source: str = \"DIRECT_SNOMED\" # DIRECT_SNOMED | NONE\n\n\n@dataclass\nclass DirectorateAssignment:\n \"\"\"Result of directorate assignment for a patient-drug combination.\"\"\"\n upid: str\n drug_name: str\n directorate: Optional[str]\n search_term: Optional[str] = None\n source: str = \"FALLBACK\" # DIAGNOSIS | FALLBACK\n snomed_code: Optional[str] = None\n event_date: Optional[datetime] = None\n\n\ndef get_drug_clusters(\n drug_name: str,\n db_manager: Optional[DatabaseManager] = None\n) -> list[dict]:\n \"\"\"\n Get all SNOMED cluster mappings for a drug from local SQLite.\n\n Args:\n drug_name: Drug name to look up (case-insensitive)\n db_manager: Optional DatabaseManager (defaults to default_db_manager)\n\n Returns:\n List of dicts with keys: drug_name, indication, cluster_id,\n cluster_description, nice_ta_reference\n \"\"\"\n if db_manager is None:\n db_manager = default_db_manager\n\n query = \"\"\"\n SELECT drug_name, indication, cluster_id, cluster_description, nice_ta_reference\n FROM ref_drug_indication_clusters\n WHERE UPPER(drug_name) = UPPER(?)\n ORDER BY indication, cluster_id\n \"\"\"\n\n try:\n with db_manager.get_connection() as conn:\n cursor = conn.execute(query, (drug_name,))\n rows = cursor.fetchall()\n\n results = []\n for row in rows:\n results.append({\n \"drug_name\": row[\"drug_name\"],\n \"indication\": row[\"indication\"],\n \"cluster_id\": row[\"cluster_id\"],\n \"cluster_description\": row[\"cluster_description\"],\n \"nice_ta_reference\": row[\"nice_ta_reference\"],\n })\n\n logger.debug(f\"Found {len(results)} cluster mappings for drug '{drug_name}'\")\n return results\n\n except Exception as e:\n logger.error(f\"Error getting clusters for drug '{drug_name}': {e}\")\n return []\n\n\ndef get_drug_cluster_ids(\n drug_name: str,\n db_manager: Optional[DatabaseManager] = None\n) -> list[str]:\n \"\"\"\n Get unique cluster IDs for a drug.\n\n Args:\n drug_name: Drug name to look up\n db_manager: Optional DatabaseManager\n\n Returns:\n List of unique cluster IDs\n \"\"\"\n clusters = get_drug_clusters(drug_name, db_manager)\n return list(set(c[\"cluster_id\"] for c in clusters))\n\n\ndef get_drug_snomed_codes(\n drug_name: str,\n db_manager: Optional[DatabaseManager] = None\n) -> list[DrugSnomedMapping]:\n \"\"\"\n Get all SNOMED codes for a drug from local ref_drug_snomed_mapping table.\n\n This uses the enriched mapping CSV data loaded into SQLite, which provides\n direct SNOMED-to-drug mappings with Search_Term and PrimaryDirectorate.\n\n Args:\n drug_name: Drug name to look up (case-insensitive, matches cleaned_drug_name)\n db_manager: Optional DatabaseManager (defaults to default_db_manager)\n\n Returns:\n List of DrugSnomedMapping with snomed_code, snomed_description,\n search_term, primary_directorate, indication, ta_id\n \"\"\"\n if db_manager is None:\n db_manager = default_db_manager\n\n query = \"\"\"\n SELECT DISTINCT\n snomed_code,\n snomed_description,\n search_term,\n primary_directorate,\n indication,\n ta_id\n FROM ref_drug_snomed_mapping\n WHERE UPPER(cleaned_drug_name) = UPPER(?)\n OR UPPER(drug_name) = UPPER(?)\n ORDER BY search_term, snomed_code\n \"\"\"\n\n try:\n with db_manager.get_connection() as conn:\n cursor = conn.execute(query, (drug_name, drug_name))\n rows = cursor.fetchall()\n\n results = []\n for row in rows:\n results.append(DrugSnomedMapping(\n snomed_code=row[\"snomed_code\"],\n snomed_description=row[\"snomed_description\"] or \"\",\n search_term=row[\"search_term\"] or \"\",\n primary_directorate=row[\"primary_directorate\"] or \"\",\n indication=row[\"indication\"] or \"\",\n ta_id=row[\"ta_id\"] or \"\",\n ))\n\n logger.debug(f\"Found {len(results)} SNOMED mappings for drug '{drug_name}'\")\n return results\n\n except Exception as e:\n logger.error(f\"Error getting SNOMED codes for drug '{drug_name}': {e}\")\n return []\n\n\ndef patient_has_indication_direct(\n patient_pseudonym: str,\n drug_snomed_mappings: list[DrugSnomedMapping],\n connector: Optional[SnowflakeConnector] = None,\n before_date: Optional[date] = None,\n) -> DirectSnomedMatchResult:\n \"\"\"\n Check if patient has any of the SNOMED codes in their GP records.\n\n This is the direct SNOMED lookup - it queries PrimaryCareClinicalCoding\n for exact SNOMED code matches (not via cluster). Returns the most recent\n match by EventDateTime if multiple matches exist.\n\n Args:\n patient_pseudonym: Patient's pseudonymised NHS number\n drug_snomed_mappings: List of DrugSnomedMapping from get_drug_snomed_codes()\n connector: Optional SnowflakeConnector (defaults to singleton)\n before_date: Optional date - only check diagnoses before this date\n\n Returns:\n DirectSnomedMatchResult with match details (most recent by EventDateTime)\n \"\"\"\n result = DirectSnomedMatchResult(\n patient_pseudonym=patient_pseudonym,\n matched=False,\n source=\"NONE\",\n )\n\n if not drug_snomed_mappings:\n return result\n\n if not SNOWFLAKE_AVAILABLE:\n logger.warning(\"Snowflake connector not available\")\n return result\n\n if not is_snowflake_configured():\n logger.warning(\"Snowflake not configured - cannot check GP records\")\n return result\n\n if connector is None:\n connector = get_connector()\n\n # Build lookup dict for mapping snomed_code -> (search_term, primary_directorate, snomed_description)\n snomed_lookup = {\n m.snomed_code: (m.search_term, m.primary_directorate, m.snomed_description)\n for m in drug_snomed_mappings\n }\n\n # Get unique SNOMED codes\n snomed_codes = list(snomed_lookup.keys())\n\n # Build placeholders for SNOMED codes\n placeholders = \", \".join([\"%s\"] * len(snomed_codes))\n\n # Query to find most recent matching SNOMED code in GP records\n query = f'''\n SELECT\n \"SNOMEDCode\",\n \"EventDateTime\"\n FROM DATA_HUB.PHM.\"PrimaryCareClinicalCoding\"\n WHERE \"PatientPseudonym\" = %s\n AND \"SNOMEDCode\" IN ({placeholders})\n '''\n\n params: list = [patient_pseudonym] + snomed_codes\n\n if before_date:\n query += ' AND \"EventDateTime\" < %s'\n params.append(before_date.isoformat())\n\n query += ' ORDER BY \"EventDateTime\" DESC LIMIT 1'\n\n try:\n results = connector.execute_dict(query, tuple(params))\n\n if results:\n row = results[0]\n matched_code = row.get(\"SNOMEDCode\")\n event_dt = row.get(\"EventDateTime\")\n\n if matched_code and matched_code in snomed_lookup:\n search_term, primary_dir, snomed_desc = snomed_lookup[matched_code]\n\n return DirectSnomedMatchResult(\n patient_pseudonym=patient_pseudonym,\n matched=True,\n snomed_code=matched_code,\n snomed_description=snomed_desc,\n search_term=search_term,\n primary_directorate=primary_dir,\n event_date=event_dt,\n source=\"DIRECT_SNOMED\",\n )\n\n return result\n\n except Exception as e:\n logger.error(f\"Error checking direct SNOMED for patient '{patient_pseudonym}': {e}\")\n return result\n\n\ndef get_directorate_from_diagnosis(\n upid: str,\n drug_name: str,\n connector: Optional[SnowflakeConnector] = None,\n db_manager: Optional[DatabaseManager] = None,\n before_date: Optional[date] = None,\n) -> DirectorateAssignment:\n \"\"\"\n Get directorate assignment for a patient-drug combination using diagnosis-based lookup.\n\n This function attempts to assign a directorate based on the patient's GP records\n (direct SNOMED code matching). If no match is found, it returns a FALLBACK result\n indicating that the caller should use alternative assignment methods (e.g.,\n department_identification() from tools/data.py).\n\n Workflow:\n 1. Get all SNOMED codes for the drug from ref_drug_snomed_mapping\n 2. Query patient's GP records for matching SNOMED codes\n 3. If match found  return diagnosis-based directorate and search_term\n 4. If no match  return FALLBACK result (caller handles fallback logic)\n\n Args:\n upid: Patient's unique patient ID (Provider Code[:3] + PersonKey)\n drug_name: Drug name to look up\n connector: Optional SnowflakeConnector (defaults to singleton)\n db_manager: Optional DatabaseManager (defaults to default_db_manager)\n before_date: Optional date - only check diagnoses before this date\n\n Returns:\n DirectorateAssignment with directorate, search_term, and source\n \"\"\"\n result = DirectorateAssignment(\n upid=upid,\n drug_name=drug_name,\n directorate=None,\n source=\"FALLBACK\",\n )\n\n # Step 1: Get SNOMED codes for the drug\n drug_snomed_mappings = get_drug_snomed_codes(drug_name, db_manager)\n\n if not drug_snomed_mappings:\n logger.debug(f\"No SNOMED mappings found for drug '{drug_name}' - using fallback\")\n return result\n\n # Step 2: Check Snowflake availability\n if not SNOWFLAKE_AVAILABLE:\n logger.debug(\"Snowflake not available - using fallback\")\n return result\n\n if not is_snowflake_configured():\n logger.debug(\"Snowflake not configured - using fallback\")\n return result\n\n # Step 3: Get patient pseudonym from UPID\n # UPID format is Provider Code (3 chars) + PersonKey\n # We need to query Snowflake to get the PatientPseudonym for this PersonKey\n # However, patient_has_indication_direct expects PatientPseudonym, not UPID\n # For now, we'll use UPID as the identifier - the actual integration\n # will need to happen at the DataFrame level where we have PersonKey\n #\n # NOTE: This function will be called from the pipeline where we have\n # access to PatientPseudonym. The UPID is passed for logging/tracking.\n\n # Actually, looking at the pipeline, we need PatientPseudonym, not UPID.\n # The caller should pass the PatientPseudonym or we need to look it up.\n # For now, let's assume the caller will use this in a batch context\n # where they can map UPID -> PatientPseudonym.\n\n # Let me reconsider: the function signature takes UPID but we need\n # PatientPseudonym for Snowflake. In the pipeline context (fetch_and_transform_data),\n # we'll have the PersonKey column which IS the PatientPseudonym.\n # So UPID = ProviderCode[:3] + PersonKey, and PersonKey = PatientPseudonym.\n #\n # We can extract PatientPseudonym from UPID by removing the first 3 chars.\n patient_pseudonym = upid[3:] if len(upid) > 3 else upid\n\n # Step 4: Check patient's GP records for matching SNOMED codes\n match_result = patient_has_indication_direct(\n patient_pseudonym=patient_pseudonym,\n drug_snomed_mappings=drug_snomed_mappings,\n connector=connector,\n before_date=before_date,\n )\n\n if match_result.matched and match_result.primary_directorate:\n return DirectorateAssignment(\n upid=upid,\n drug_name=drug_name,\n directorate=match_result.primary_directorate,\n search_term=match_result.search_term,\n source=\"DIAGNOSIS\",\n snomed_code=match_result.snomed_code,\n event_date=match_result.event_date,\n )\n\n # No match found - return fallback result\n return result\n\n\ndef get_cluster_snomed_codes(\n cluster_id: str,\n connector: Optional[SnowflakeConnector] = None,\n use_cache: bool = True,\n) -> ClusterSnomedCodes:\n \"\"\"\n Get all SNOMED codes for a cluster from Snowflake.\n\n Queries the ClinicalCodingClusterSnomedCodes table to get all SNOMED codes\n that belong to the specified cluster.\n\n Args:\n cluster_id: Cluster ID to look up (e.g., 'RARTH_COD', 'PSORIASIS_COD')\n connector: Optional SnowflakeConnector (defaults to singleton)\n use_cache: Whether to use cached results (default True)\n\n Returns:\n ClusterSnomedCodes with list of SNOMED codes and descriptions\n \"\"\"\n if not SNOWFLAKE_AVAILABLE:\n logger.warning(\"Snowflake connector not available\")\n return ClusterSnomedCodes(cluster_id=cluster_id, cluster_description=\"\")\n\n if not is_snowflake_configured():\n logger.warning(\"Snowflake not configured - cannot get cluster codes\")\n return ClusterSnomedCodes(cluster_id=cluster_id, cluster_description=\"\")\n\n # Check cache first\n cache_key = f\"cluster_snomed_{cluster_id}\"\n if use_cache and is_cache_enabled():\n cache = get_cache()\n cached = cache.get(cache_key)\n if cached is not None and len(cached) > 0:\n logger.debug(f\"Using cached SNOMED codes for cluster '{cluster_id}'\")\n cached_dict = cached[0] # First element is our data dict\n return ClusterSnomedCodes(\n cluster_id=cluster_id,\n cluster_description=str(cached_dict.get(\"description\", \"\")),\n snomed_codes=list(cached_dict.get(\"codes\", [])),\n snomed_descriptions=dict(cached_dict.get(\"descriptions\", {})),\n )\n\n if connector is None:\n connector = get_connector()\n\n query = '''\n SELECT DISTINCT\n \"Cluster_ID\",\n \"Cluster_Description\",\n \"SNOMEDCode\",\n \"SNOMEDDescription\"\n FROM DATA_HUB.PHM.\"ClinicalCodingClusterSnomedCodes\"\n WHERE \"Cluster_ID\" = %s\n ORDER BY \"SNOMEDCode\"\n '''\n\n try:\n results = connector.execute_dict(query, (cluster_id,))\n\n if not results:\n logger.warning(f\"No SNOMED codes found for cluster '{cluster_id}'\")\n return ClusterSnomedCodes(cluster_id=cluster_id, cluster_description=\"\")\n\n codes = []\n descriptions = {}\n description = results[0].get(\"Cluster_Description\", \"\") if results else \"\"\n\n for row in results:\n code = row.get(\"SNOMEDCode\")\n if code:\n codes.append(code)\n descriptions[code] = row.get(\"SNOMEDDescription\", \"\")\n\n logger.info(f\"Found {len(codes)} SNOMED codes for cluster '{cluster_id}'\")\n\n # Cache the results (using query-based cache with fake params)\n if use_cache and is_cache_enabled():\n cache = get_cache()\n cache_data = [{\n \"description\": description,\n \"codes\": codes,\n \"descriptions\": descriptions,\n }]\n cache.set(cache_key, None, cache_data) # type: ignore[arg-type]\n\n return ClusterSnomedCodes(\n cluster_id=cluster_id,\n cluster_description=description,\n snomed_codes=codes,\n snomed_descriptions=descriptions,\n )\n\n except Exception as e:\n logger.error(f\"Error getting SNOMED codes for cluster '{cluster_id}': {e}\")\n return ClusterSnomedCodes(cluster_id=cluster_id, cluster_description=\"\")\n\n\ndef patient_has_indication(\n patient_pseudonym: str,\n cluster_ids: list[str],\n connector: Optional[SnowflakeConnector] = None,\n before_date: Optional[date] = None,\n) -> tuple[bool, Optional[str], Optional[str], Optional[str]]:\n \"\"\"\n Check if a patient has any SNOMED codes from the specified clusters in GP records.\n\n Args:\n patient_pseudonym: Patient's pseudonymised NHS number\n cluster_ids: List of cluster IDs to check against\n connector: Optional SnowflakeConnector\n before_date: Optional date - only check diagnoses before this date\n\n Returns:\n Tuple of (has_indication, matched_cluster_id, matched_snomed_code, matched_description)\n \"\"\"\n if not SNOWFLAKE_AVAILABLE or not is_snowflake_configured():\n return False, None, None, None\n\n if not cluster_ids:\n return False, None, None, None\n\n if connector is None:\n connector = get_connector()\n\n # Build placeholders for cluster IDs\n placeholders = \", \".join([\"%s\"] * len(cluster_ids))\n\n # Query to check if patient has any matching SNOMED code\n query = f'''\n SELECT\n pc.\"SNOMEDCode\",\n cc.\"Cluster_ID\",\n cc.\"SNOMEDDescription\"\n FROM DATA_HUB.PHM.\"PrimaryCareClinicalCoding\" pc\n INNER JOIN DATA_HUB.PHM.\"ClinicalCodingClusterSnomedCodes\" cc\n ON pc.\"SNOMEDCode\" = cc.\"SNOMEDCode\"\n WHERE pc.\"PatientPseudonym\" = %s\n AND cc.\"Cluster_ID\" IN ({placeholders})\n '''\n\n params = [patient_pseudonym] + cluster_ids\n\n if before_date:\n query += ' AND pc.\"EventDateTime\" < %s'\n params.append(before_date.isoformat())\n\n query += ' LIMIT 1'\n\n try:\n results = connector.execute_dict(query, tuple(params))\n\n if results:\n row = results[0]\n return (\n True,\n row.get(\"Cluster_ID\"),\n row.get(\"SNOMEDCode\"),\n row.get(\"SNOMEDDescription\"),\n )\n\n return False, None, None, None\n\n except Exception as e:\n logger.error(f\"Error checking indication for patient '{patient_pseudonym}': {e}\")\n return False, None, None, None\n\n\ndef validate_indication(\n patient_pseudonym: str,\n drug_name: str,\n connector: Optional[SnowflakeConnector] = None,\n db_manager: Optional[DatabaseManager] = None,\n before_date: Optional[date] = None,\n) -> IndicationValidationResult:\n \"\"\"\n Validate that a patient has an appropriate indication for a drug.\n\n Full validation workflow:\n 1. Get drug's valid indication clusters from local mapping\n 2. Check if patient has any matching SNOMED codes in GP records\n 3. Return detailed validation result\n\n Args:\n patient_pseudonym: Patient's pseudonymised NHS number\n drug_name: Drug name to validate indication for\n connector: Optional SnowflakeConnector\n db_manager: Optional DatabaseManager\n before_date: Optional date - only check diagnoses before this date\n\n Returns:\n IndicationValidationResult with validation details\n \"\"\"\n result = IndicationValidationResult(\n patient_pseudonym=patient_pseudonym,\n drug_name=drug_name,\n has_valid_indication=False,\n )\n\n # Step 1: Get drug's cluster mappings\n cluster_ids = get_drug_cluster_ids(drug_name, db_manager)\n\n if not cluster_ids:\n result.error_message = f\"No cluster mappings found for drug '{drug_name}'\"\n result.source = \"NONE\"\n return result\n\n result.checked_clusters = cluster_ids\n\n # Step 2: Check Snowflake availability\n if not SNOWFLAKE_AVAILABLE:\n result.error_message = \"Snowflake connector not installed\"\n result.source = \"NONE\"\n return result\n\n if not is_snowflake_configured():\n result.error_message = \"Snowflake not configured\"\n result.source = \"NONE\"\n return result\n\n # Step 3: Check patient GP records\n has_indication, matched_cluster, matched_code, matched_desc = patient_has_indication(\n patient_pseudonym=patient_pseudonym,\n cluster_ids=cluster_ids,\n connector=connector,\n before_date=before_date,\n )\n\n result.has_valid_indication = has_indication\n result.matched_cluster_id = matched_cluster\n result.matched_snomed_code = matched_code\n result.matched_snomed_description = matched_desc\n result.source = \"GP_SNOMED\" if has_indication else \"NONE\"\n\n return result\n\n\ndef get_indication_match_rate(\n drug_name: str,\n patient_pseudonyms: list[str],\n connector: Optional[SnowflakeConnector] = None,\n db_manager: Optional[DatabaseManager] = None,\n sample_unmatched_count: int = 10,\n) -> DrugIndicationMatchRate:\n \"\"\"\n Calculate indication match rate for a drug across a list of patients.\n\n Args:\n drug_name: Drug name to check\n patient_pseudonyms: List of patient pseudonymised NHS numbers\n connector: Optional SnowflakeConnector\n db_manager: Optional DatabaseManager\n sample_unmatched_count: Number of unmatched patient IDs to include in sample\n\n Returns:\n DrugIndicationMatchRate with match statistics\n \"\"\"\n if connector is None and SNOWFLAKE_AVAILABLE and is_snowflake_configured():\n connector = get_connector()\n\n cluster_ids = get_drug_cluster_ids(drug_name, db_manager)\n\n total = len(patient_pseudonyms)\n matched = 0\n unmatched = 0\n sample_unmatched: list[str] = []\n\n if not cluster_ids:\n logger.warning(f\"No cluster mappings for drug '{drug_name}' - all patients will be unmatched\")\n return DrugIndicationMatchRate(\n drug_name=drug_name,\n total_patients=total,\n patients_with_indication=0,\n patients_without_indication=total,\n match_rate=0.0,\n clusters_checked=[],\n sample_unmatched=patient_pseudonyms[:sample_unmatched_count],\n )\n\n for i, pseudonym in enumerate(patient_pseudonyms):\n if i > 0 and i % 100 == 0:\n logger.info(f\"Validating indications: {i}/{total} ({100*i/total:.1f}%)\")\n\n has_indication, _, _, _ = patient_has_indication(\n patient_pseudonym=pseudonym,\n cluster_ids=cluster_ids,\n connector=connector,\n )\n\n if has_indication:\n matched += 1\n else:\n unmatched += 1\n if len(sample_unmatched) < sample_unmatched_count:\n sample_unmatched.append(pseudonym)\n\n match_rate = matched / total if total > 0 else 0.0\n\n logger.info(f\"Indication match rate for '{drug_name}': {100*match_rate:.1f}% ({matched}/{total})\")\n\n return DrugIndicationMatchRate(\n drug_name=drug_name,\n total_patients=total,\n patients_with_indication=matched,\n patients_without_indication=unmatched,\n match_rate=match_rate,\n clusters_checked=cluster_ids,\n sample_unmatched=sample_unmatched,\n )\n\n\ndef batch_validate_indications(\n patient_drug_pairs: list[tuple[str, str]],\n connector: Optional[SnowflakeConnector] = None,\n db_manager: Optional[DatabaseManager] = None,\n progress_callback: Optional[Callable[[int, int], None]] = None,\n) -> list[IndicationValidationResult]:\n \"\"\"\n Validate indications for multiple patient-drug pairs efficiently.\n\n Args:\n patient_drug_pairs: List of (patient_pseudonym, drug_name) tuples\n connector: Optional SnowflakeConnector\n db_manager: Optional DatabaseManager\n progress_callback: Optional callback(current, total) for progress updates\n\n Returns:\n List of IndicationValidationResult for each pair\n \"\"\"\n results = []\n total = len(patient_drug_pairs)\n\n # Cache cluster lookups by drug\n drug_clusters_cache = {}\n\n for i, (pseudonym, drug_name) in enumerate(patient_drug_pairs):\n if progress_callback:\n progress_callback(i + 1, total)\n\n # Get clusters from cache or lookup\n drug_upper = drug_name.upper()\n if drug_upper not in drug_clusters_cache:\n drug_clusters_cache[drug_upper] = get_drug_cluster_ids(drug_name, db_manager)\n\n cluster_ids = drug_clusters_cache[drug_upper]\n\n if not cluster_ids:\n results.append(IndicationValidationResult(\n patient_pseudonym=pseudonym,\n drug_name=drug_name,\n has_valid_indication=False,\n source=\"NONE\",\n error_message=f\"No cluster mappings for drug '{drug_name}'\",\n ))\n continue\n\n # Check patient indication\n has_indication, matched_cluster, matched_code, matched_desc = patient_has_indication(\n patient_pseudonym=pseudonym,\n cluster_ids=cluster_ids,\n connector=connector,\n )\n\n results.append(IndicationValidationResult(\n patient_pseudonym=pseudonym,\n drug_name=drug_name,\n has_valid_indication=has_indication,\n matched_cluster_id=matched_cluster,\n matched_snomed_code=matched_code,\n matched_snomed_description=matched_desc,\n checked_clusters=cluster_ids,\n source=\"GP_SNOMED\" if has_indication else \"NONE\",\n ))\n\n matched_count = sum(1 for r in results if r.has_valid_indication)\n logger.info(f\"Batch validation complete: {matched_count}/{total} ({100*matched_count/total:.1f}%) with valid indications\")\n\n return results\n\n\ndef get_available_clusters(\n connector: Optional[SnowflakeConnector] = None,\n) -> list[dict]:\n \"\"\"\n Get list of all available SNOMED clusters from Snowflake.\n\n Returns:\n List of dicts with cluster_id, cluster_description, code_count\n \"\"\"\n if not SNOWFLAKE_AVAILABLE or not is_snowflake_configured():\n logger.warning(\"Snowflake not available - cannot list clusters\")\n return []\n\n if connector is None:\n connector = get_connector()\n\n query = '''\n SELECT\n \"Cluster_ID\",\n \"Cluster_Description\",\n COUNT(DISTINCT \"SNOMEDCode\") as code_count\n FROM DATA_HUB.PHM.\"ClinicalCodingClusterSnomedCodes\"\n GROUP BY \"Cluster_ID\", \"Cluster_Description\"\n ORDER BY \"Cluster_ID\"\n '''\n\n try:\n results = connector.execute_dict(query)\n\n clusters = []\n for row in results:\n clusters.append({\n \"cluster_id\": row.get(\"Cluster_ID\"),\n \"cluster_description\": row.get(\"Cluster_Description\"),\n \"code_count\": row.get(\"code_count\", 0),\n })\n\n logger.info(f\"Found {len(clusters)} available SNOMED clusters\")\n return clusters\n\n except Exception as e:\n logger.error(f\"Error getting available clusters: {e}\")\n return []\n\n\ndef batch_lookup_indication_groups(\n df: \"pd.DataFrame\",\n connector: Optional[SnowflakeConnector] = None,\n db_manager: Optional[DatabaseManager] = None,\n batch_size: int = 500,\n) -> \"pd.DataFrame\":\n \"\"\"\n Batch lookup GP diagnosis-based indication groups for a DataFrame of patients.\n\n This is the efficient batch version of get_directorate_from_diagnosis().\n Instead of querying Snowflake per patient, it batches the lookups for performance.\n\n Strategy:\n 1. Get all unique (PersonKey, Drug Name) pairs from DataFrame\n 2. For each unique drug, get all SNOMED codes from local SQLite\n 3. Build batched Snowflake queries to check GP records\n 4. Return indication_df mapping UPID  Indication_Group\n\n For unmatched patients, Indication_Group will be their Directory (with suffix).\n\n Args:\n df: DataFrame with columns: UPID, Drug Name, Directory, PersonKey\n connector: Optional SnowflakeConnector (defaults to singleton)\n db_manager: Optional DatabaseManager (defaults to default_db_manager)\n batch_size: Number of patients per Snowflake query batch\n\n Returns:\n DataFrame with columns: UPID, Indication_Group, Source\n - Indication_Group: Search_Term (if matched) or \"Directory (no GP dx)\" (if not)\n - Source: \"DIAGNOSIS\" or \"FALLBACK\"\n \"\"\"\n import pandas as pd\n\n if db_manager is None:\n db_manager = default_db_manager\n\n logger.info(f\"Starting batch indication lookup for {len(df)} records...\")\n\n # Step 1: Get unique (UPID, Drug Name, PseudoNHSNoLinked, Directory) combinations\n # We need PseudoNHSNoLinked to query Snowflake - this matches PatientPseudonym in GP records\n # Note: PersonKey is LocalPatientID which is provider-specific and does NOT match GP records\n if 'PseudoNHSNoLinked' not in df.columns:\n logger.error(\"DataFrame missing 'PseudoNHSNoLinked' column - cannot lookup GP records\")\n # Return fallback for all patients\n result_df = df[['UPID', 'Directory']].drop_duplicates().copy()\n result_df['Indication_Group'] = result_df['Directory'] + \" (no GP dx)\"\n result_df['Source'] = \"FALLBACK\"\n return result_df[['UPID', 'Indication_Group', 'Source']]\n\n # Get unique patient-drug combinations (we need one lookup per patient-drug pair)\n unique_pairs = df[['UPID', 'Drug Name', 'PseudoNHSNoLinked', 'Directory']].drop_duplicates()\n logger.info(f\"Found {len(unique_pairs)} unique patient-drug combinations\")\n\n # Step 2: Get all unique drugs and their SNOMED codes\n unique_drugs = unique_pairs['Drug Name'].unique()\n logger.info(f\"Building SNOMED lookup for {len(unique_drugs)} unique drugs...\")\n\n # Build drug -> list of DrugSnomedMapping dict\n drug_snomed_map: dict[str, list[DrugSnomedMapping]] = {}\n all_snomed_codes: set[str] = set()\n snomed_to_drug_searchterm: dict[str, list[tuple[str, str, str]]] = {} # snomed -> [(drug, search_term, primary_dir), ...]\n\n for drug_name in unique_drugs:\n mappings = get_drug_snomed_codes(drug_name, db_manager)\n drug_snomed_map[drug_name] = mappings\n\n for m in mappings:\n all_snomed_codes.add(m.snomed_code)\n if m.snomed_code not in snomed_to_drug_searchterm:\n snomed_to_drug_searchterm[m.snomed_code] = []\n snomed_to_drug_searchterm[m.snomed_code].append(\n (drug_name, m.search_term, m.primary_directorate)\n )\n\n logger.info(f\"Total SNOMED codes to check: {len(all_snomed_codes)}\")\n\n # Step 3: Check Snowflake availability\n if not SNOWFLAKE_AVAILABLE or not is_snowflake_configured():\n logger.warning(\"Snowflake not available - returning fallback for all patients\")\n result_df = unique_pairs[['UPID', 'Directory']].copy()\n result_df['Indication_Group'] = result_df['Directory'] + \" (no GP dx)\"\n result_df['Source'] = \"FALLBACK\"\n return result_df[['UPID', 'Indication_Group', 'Source']].drop_duplicates(subset=['UPID'])\n\n if connector is None:\n connector = get_connector()\n\n # Step 4: Query GP records for all patients in batches\n # The query finds the most recent matching SNOMED code for each patient\n\n # Get unique PseudoNHSNoLinked values (each = one patient in GP records)\n unique_patients = unique_pairs[['PseudoNHSNoLinked', 'UPID', 'Directory']].drop_duplicates(subset=['PseudoNHSNoLinked'])\n patient_pseudonyms = unique_patients['PseudoNHSNoLinked'].tolist()\n\n logger.info(f\"Querying GP records for {len(patient_pseudonyms)} unique patients in batches of {batch_size}...\")\n\n # Results dict: PersonKey -> (snomed_code, event_date)\n gp_matches: dict[str, tuple[str, Any]] = {}\n\n # Convert SNOMED codes to list for query\n snomed_list = list(all_snomed_codes)\n\n if not snomed_list:\n logger.warning(\"No SNOMED codes to check - returning fallback for all patients\")\n result_df = unique_pairs[['UPID', 'Directory']].copy()\n result_df['Indication_Group'] = result_df['Directory'] + \" (no GP dx)\"\n result_df['Source'] = \"FALLBACK\"\n return result_df[['UPID', 'Indication_Group', 'Source']].drop_duplicates(subset=['UPID'])\n\n # Build SNOMED IN clause (reused across batches)\n snomed_placeholders = \", \".join([\"%s\"] * len(snomed_list))\n\n # Process patients in batches\n for batch_start in range(0, len(patient_pseudonyms), batch_size):\n batch_end = min(batch_start + batch_size, len(patient_pseudonyms))\n batch_pseudonyms = patient_pseudonyms[batch_start:batch_end]\n\n logger.info(f\"Batch {batch_start//batch_size + 1}: patients {batch_start} to {batch_end}\")\n\n # Build patient IN clause\n patient_placeholders = \", \".join([\"%s\"] * len(batch_pseudonyms))\n\n # Query to find all matching SNOMED codes for these patients\n # We'll get all matches and pick the most recent per patient in Python\n query = f'''\n SELECT\n \"PatientPseudonym\",\n \"SNOMEDCode\",\n \"EventDateTime\"\n FROM DATA_HUB.PHM.\"PrimaryCareClinicalCoding\"\n WHERE \"PatientPseudonym\" IN ({patient_placeholders})\n AND \"SNOMEDCode\" IN ({snomed_placeholders})\n ORDER BY \"PatientPseudonym\", \"EventDateTime\" DESC\n '''\n\n params = tuple(batch_pseudonyms) + tuple(snomed_list)\n\n try:\n results = connector.execute_dict(query, params)\n\n # Process results - pick most recent per patient\n for row in results:\n person_key = row.get(\"PatientPseudonym\")\n snomed_code = row.get(\"SNOMEDCode\")\n event_date = row.get(\"EventDateTime\")\n\n if person_key and snomed_code:\n # Keep only if we haven't seen this patient yet (first = most recent due to ORDER BY)\n if person_key not in gp_matches:\n gp_matches[person_key] = (snomed_code, event_date)\n\n except Exception as e:\n logger.error(f\"Error querying GP records for batch: {e}\")\n # Continue with other batches\n\n logger.info(f\"Found GP matches for {len(gp_matches)} patients\")\n\n # Step 5: Build result DataFrame\n # For each unique_pair, determine Indication_Group based on match status\n results_list = []\n\n # We need to dedupe by UPID - a patient might be on multiple drugs\n # Strategy: For each UPID, use the most recent match (if any)\n upid_to_match: dict[str, tuple[str, str]] = {} # UPID -> (Indication_Group, Source)\n\n for _, row in unique_pairs.iterrows():\n upid = row['UPID']\n drug_name = row['Drug Name']\n patient_pseudonym = row['PseudoNHSNoLinked']\n directory = row['Directory']\n\n # Check if patient has GP match (using PseudoNHSNoLinked which matches PatientPseudonym in GP)\n if patient_pseudonym in gp_matches:\n matched_snomed, event_date = gp_matches[patient_pseudonym]\n\n # Find the search_term for this SNOMED code and drug\n # (A SNOMED code might map to multiple drugs with different search_terms)\n if matched_snomed in snomed_to_drug_searchterm:\n # Look for match with current drug first\n search_term = None\n for drug, st, pd in snomed_to_drug_searchterm[matched_snomed]:\n if drug.upper() == drug_name.upper():\n search_term = st\n break\n # If no drug-specific match, use any match\n if search_term is None:\n search_term = snomed_to_drug_searchterm[matched_snomed][0][1]\n\n # Only update if we don't have a match for this UPID yet\n if upid not in upid_to_match:\n upid_to_match[upid] = (search_term, \"DIAGNOSIS\")\n else:\n # Shouldn't happen but fallback just in case\n if upid not in upid_to_match:\n upid_to_match[upid] = (directory + \" (no GP dx)\", \"FALLBACK\")\n else:\n # No GP match - use fallback\n if upid not in upid_to_match:\n upid_to_match[upid] = (directory + \" (no GP dx)\", \"FALLBACK\")\n\n # Build result DataFrame\n for upid, (indication_group, source) in upid_to_match.items():\n results_list.append({\n 'UPID': upid,\n 'Indication_Group': indication_group,\n 'Source': source,\n })\n\n result_df = pd.DataFrame(results_list)\n\n # Log statistics\n diagnosis_count = len([s for s in result_df['Source'] if s == \"DIAGNOSIS\"])\n fallback_count = len([s for s in result_df['Source'] if s == \"FALLBACK\"])\n total = len(result_df)\n\n logger.info(f\"Indication lookup complete:\")\n logger.info(f\" Total unique patients: {total}\")\n logger.info(f\" DIAGNOSIS matches: {diagnosis_count} ({100*diagnosis_count/total:.1f}%)\")\n logger.info(f\" FALLBACK (no GP match): {fallback_count} ({100*fallback_count/total:.1f}%)\")\n\n return result_df\n\n\n# === Drug-to-indication mapping from DimSearchTerm.csv ===\n\n\n# Merge related Search_Terms into canonical names.\n# Asthma variants are clinically the same condition at different severity levels.\n# Urticaria is a separate condition  do NOT merge with asthma.\nSEARCH_TERM_MERGE_MAP: dict[str, str] = {\n \"allergic asthma\": \"asthma\",\n \"severe persistent allergic asthma\": \"asthma\",\n}\n\n\ndef load_drug_indication_mapping(\n csv_path: Optional[str] = None,\n) -> tuple[dict[str, list[str]], dict[str, list[str]]]:\n \"\"\"\n Load the drug-to-Search_Term mapping from DimSearchTerm.csv.\n\n Builds two lookup dicts:\n - fragment_to_search_terms: drug fragment (UPPERCASE) -> list of Search_Terms containing it\n - search_term_to_fragments: search_term -> list of drug fragments (UPPERCASE)\n\n DimSearchTerm.csv has columns: Search_Term, CleanedDrugName, PrimaryDirectorate\n CleanedDrugName is pipe-separated (e.g., \"ADALIMUMAB|GOLIMUMAB|IXEKIZUMAB\").\n\n Note: A Search_Term can appear multiple times with different PrimaryDirectorates\n (e.g., \"diabetes\" appears under both DIABETIC MEDICINE and OPHTHALMOLOGY).\n Drug fragments from all rows for the same Search_Term are combined.\n\n Asthma-related Search_Terms (\"allergic asthma\", \"severe persistent allergic asthma\")\n are merged into \"asthma\" to match the CLUSTER_MAPPING_SQL normalization.\n \"urticaria\" stays separate.\n\n Args:\n csv_path: Path to DimSearchTerm.csv. Defaults to data/DimSearchTerm.csv.\n\n Returns:\n Tuple of (fragment_to_search_terms, search_term_to_fragments)\n \"\"\"\n if csv_path is None:\n csv_path = str(Path(__file__).parent.parent / \"data\" / \"DimSearchTerm.csv\")\n\n fragment_to_search_terms: dict[str, list[str]] = {}\n search_term_to_fragments: dict[str, list[str]] = {}\n\n try:\n with open(csv_path, \"r\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n for row in reader:\n search_term = row.get(\"Search_Term\", \"\").strip()\n drug_names_raw = row.get(\"CleanedDrugName\", \"\").strip()\n\n # Normalize asthma variants to canonical \"asthma\"\n search_term = SEARCH_TERM_MERGE_MAP.get(search_term, search_term)\n\n if not search_term or not drug_names_raw:\n continue\n\n fragments = [frag.strip().upper() for frag in drug_names_raw.split(\"|\") if frag.strip()]\n\n # Build search_term -> fragments (accumulate for duplicate Search_Terms)\n if search_term not in search_term_to_fragments:\n search_term_to_fragments[search_term] = []\n for frag in fragments:\n if frag not in search_term_to_fragments[search_term]:\n search_term_to_fragments[search_term].append(frag)\n\n # Build fragment -> search_terms\n for frag in fragments:\n if frag not in fragment_to_search_terms:\n fragment_to_search_terms[frag] = []\n if search_term not in fragment_to_search_terms[frag]:\n fragment_to_search_terms[frag].append(search_term)\n\n logger.info(\n f\"Loaded drug-indication mapping: {len(search_term_to_fragments)} Search_Terms, \"\n f\"{len(fragment_to_search_terms)} drug fragments\"\n )\n\n except FileNotFoundError:\n logger.error(f\"DimSearchTerm.csv not found at {csv_path}\")\n except Exception as e:\n logger.error(f\"Error loading DimSearchTerm.csv: {e}\")\n\n return fragment_to_search_terms, search_term_to_fragments\n\n\ndef get_search_terms_for_drug(\n drug_name: str,\n search_term_to_fragments: dict[str, list[str]],\n) -> list[str]:\n \"\"\"\n Get all Search_Terms that list a given drug using substring matching.\n\n Checks if any drug fragment from DimSearchTerm is a SUBSTRING of the given\n drug name (case-insensitive). This handles both exact matches (ADALIMUMAB)\n and partial fragments (PEGYLATED, INHALED).\n\n Args:\n drug_name: HCD drug name (e.g., \"ADALIMUMAB 40MG\", \"PEGYLATED LIPOSOMAL DOXORUBICIN\")\n search_term_to_fragments: Mapping of search_term -> list of drug fragments\n\n Returns:\n List of Search_Terms whose drug fragments match the drug name\n \"\"\"\n drug_name_upper = drug_name.upper()\n matched_terms: list[str] = []\n\n for search_term, fragments in search_term_to_fragments.items():\n for frag in fragments:\n if frag in drug_name_upper:\n matched_terms.append(search_term)\n break # One matching fragment is enough for this Search_Term\n\n return matched_terms\n\n\n# === NEW APPROACH: Query Snowflake directly using cluster CTE ===\n\n# The cluster query mapping (embedded from snomed_indication_mapping_query.sql)\n# This maps Search_Term -> Cluster_ID for ~148 clinical conditions\nCLUSTER_MAPPING_SQL = \"\"\"\nWITH SearchTermClusters AS (\n SELECT Search_Term, Cluster_ID FROM (VALUES\n ('acute lymphoblastic leukaemia', 'HAEMCANMORPH_COD'),\n ('acute myeloid leukaemia', 'C19HAEMCAN_COD'),\n ('acute promyelocytic leukaemia', 'HAEMCANMORPH_COD'),\n ('asthma', 'AST_COD'),\n ('allergic rhinitis', 'MILDINTAST_COD'),\n ('alzheimer''s disease', 'DEMALZ_COD'),\n ('amyloidosis', 'AMYLOID_COD'),\n ('anaemia', 'eFI2_AnaemiaTimeSensitive'),\n ('anaplastic large cell lymphoma', 'C19HAEMCAN_COD'),\n ('apixaban', 'DOACCON_COD'),\n ('aplastic anaemia', 'eFI2_AnaemiaEver'),\n ('arthritis', 'eFI2_InflammatoryArthritis'),\n ('asthma', 'eFI2_Asthma'),\n ('atopic dermatitis', 'ATOPDERM_COD'),\n ('atrial fibrillation', 'eFI2_AtrialFibrillation'),\n ('attention deficit hyperactivity disorder', 'ADHD_COD'),\n ('bipolar disorder', 'MH_COD'),\n ('bladder', 'eFI2_UrinaryIncontinence'),\n ('breast cancer', 'BRCANSCR_COD'),\n ('cardiomyopathy', 'eFI2_HarmfulDrinking'),\n ('cardiovascular disease', 'CVDRISKASS_COD'),\n ('cervical cancer', 'CSDEC_COD'),\n ('cholangiocarcinoma', 'eFI2_Cancer'),\n ('chronic kidney disease', 'CKD_COD'),\n ('chronic liver disease', 'eFI2_LiverProblems'),\n ('chronic lymphocytic leukaemia', 'EPPHAEMCAN_COD'),\n ('chronic myeloid leukaemia', 'EPPHAEMCAN_COD'),\n ('chronic obstructive pulmonary disease', 'eFI2_COPD'),\n ('colon cancer', 'eFI2_Cancer'),\n ('colorectal cancer', 'GICANREF_COD'),\n ('constipation', 'CHRONCONSTIP_COD'),\n ('covid-19', 'POSSPOSTCOVID_COD'),\n ('crohn''s disease', 'eFI2_InflammatoryBowelDisease'),\n ('cutaneous t-cell lymphoma', 'C19HAEMCAN_COD'),\n ('cystic fibrosis', 'CUST_ICB_CYSTIC_FIBROSIS'),\n ('deep vein thrombosis', 'VTE_COD'),\n ('depression', 'eFI2_Depression'),\n ('diabetes', 'eFI2_DiabetesEver'),\n ('diabetic retinopathy', 'DRSELIGIBILITY_COD'),\n ('diffuse large b-cell lymphoma', 'C19HAEMCAN_COD'),\n ('dravet syndrome', 'EPIL_COD'),\n ('drug misuse', 'ILLSUBINT_COD'),\n ('dyspepsia', 'eFI2_AbdominalPain'),\n ('epilepsy', 'eFI2_Seizures'),\n ('fallopian tube', 'STERIL_COD'),\n ('follicular lymphoma', 'C19HAEMCAN_COD'),\n ('gastric cancer', 'eFI2_Cancer'),\n ('giant cell arteritis', 'GCA_COD'),\n ('glioma', 'NHAEMCANMORPH_COD'),\n ('gout', 'eFI2_InflammatoryArthritis'),\n ('graft versus host disease', 'GVHD_COD'),\n ('granulomatosis with polyangiitis', 'WEGENERVASC_COD'),\n ('growth hormone deficiency', 'HYPOPITUITARY_COD'),\n ('hand eczema', 'ECZEMA_COD'),\n ('heart failure', 'eFI2_HeartFailure'),\n ('hepatitis b', 'HEPBCVAC_COD'),\n ('hepatocellular carcinoma', 'eFI2_Cancer'),\n ('hiv', 'PREFLANG_COD'),\n ('hodgkin lymphoma', 'HAEMCANMORPH_COD'),\n ('hormone receptor', 'eFI2_ThyroidProblems'),\n ('hypercholesterolaemia', 'CLASSFH_COD'),\n ('immune thrombocytopenia', 'ITP_COD'),\n ('influenza', 'FLUINVITE_COD'),\n ('insomnia', 'eFI2_SleepProblems'),\n ('irritable bowel syndrome', 'IBS_COD'),\n ('ischaemic stroke', 'OSTR_COD'),\n ('juvenile idiopathic arthritis', 'RARTHAD_COD'),\n ('kidney transplant', 'RENALTRANSP_COD'),\n ('leukaemia', 'eFI2_Cancer'),\n ('lung cancer', 'FTCANREF_COD'),\n ('lymphoma', 'C19HAEMCAN_COD'),\n ('macular degeneration', 'CUST_ICB_VISUAL_IMPAIRMENT'),\n ('macular oedema', 'CUST_ICB_VISUAL_IMPAIRMENT'),\n ('major depressive episodes', 'eFI2_Depression'),\n ('malignant melanoma', 'eFI2_Cancer'),\n ('malignant pleural mesothelioma', 'LUNGCAN_COD'),\n ('manic episode', 'MH_COD'),\n ('mantle cell lymphoma', 'HAEMCANMORPH_COD'),\n ('melanoma', 'eFI2_Cancer'),\n ('merkel cell carcinoma', 'C19CAN_COD'),\n ('migraine', 'eFI2_Headache'),\n ('motor neurone disease', 'MND_COD'),\n ('multiple myeloma', 'C19HAEMCAN_COD'),\n ('multiple sclerosis', 'MS_COD'),\n ('myelodysplastic', 'eFI2_AnaemiaEver'),\n ('myelofibrosis', 'MDS_COD'),\n ('myocardial infarction', 'eFI2_IschaemicHeartDisease'),\n ('myotonia', 'CNDATRISK2_COD'),\n ('narcolepsy', 'LD_COD'),\n ('neuroendocrine tumour', 'LUNGCAN_COD'),\n ('non-small cell lung cancer', 'LUNGCAN_COD'),\n ('non-small-cell lung cancer', 'FTCANREF_COD'),\n ('obesity', 'BMI30_COD'),\n ('osteoarthritis', 'CUST_ICB_OSTEOARTHRITIS'),\n ('osteoporosis', 'eFI2_Osteoporosis'),\n ('osteosarcoma', 'NHAEMCANMORPH_COD'),\n ('ovarian cancer', 'C19CAN_COD'),\n ('peripheral arterial disease', 'PADEXC_COD'),\n ('plaque psoriasis', 'PSORIASIS_COD'),\n ('polycystic kidney disease', 'EPPCONGMALF_COD'),\n ('polycythaemia vera', 'C19HAEMCAN_COD'),\n ('pregnancy', 'C19PREG_COD'),\n ('primary biliary cholangitis', 'eFI2_LiverProblems'),\n ('primary hypercholesterolaemia', 'FNFHYP_COD'),\n ('prostate cancer', 'EPPSOLIDCAN_COD'),\n ('psoriasis', 'PSORIASIS_COD'),\n ('psoriatic arthritis', 'RARTHAD_COD'),\n ('pulmonary embolism', 'eFI2_RespiratoryDiseaseTimeSensitive'),\n ('pulmonary fibrosis', 'ILD_COD'),\n ('relapsing multiple sclerosis', 'MS_COD'),\n ('renal cell carcinoma', 'C19CAN_COD'),\n ('renal transplantation', 'RENALTRANSP_COD'),\n ('retinal vein occlusion', 'CUST_ICB_VISUAL_IMPAIRMENT'),\n ('rheumatoid arthritis', 'eFI2_InflammatoryArthritis'),\n ('rivaroxaban', 'DOACCON_COD'),\n ('schizophrenia', 'MH_COD'),\n ('seizures', 'LSZFREQ_COD'),\n ('sepsis', 'C19ACTIVITY_COD'),\n ('asthma', 'SEVAST_COD'),\n ('sickle cell disease', 'SICKLE_COD'),\n ('sleep apnoea', 'CUST_ICB_NON_SEVERE_LDA'),\n ('smoking cessation', 'SMOKINGINT_COD'),\n ('soft tissue sarcoma', 'NHAEMCANMORPH_COD'),\n ('spinal muscular atrophy', 'MND_COD'),\n ('squamous cell', 'C19CAN_COD'),\n ('squamous cell carcinoma', 'C19CAN_COD'),\n ('stem cell transplant', 'ALLOTRANSP_COD'),\n ('stroke', 'eFI2_Stroke'),\n ('systemic lupus erythematosus', 'SLUPUS_COD'),\n ('systemic mastocytosis', 'HAEMCANMORPH_COD'),\n ('thrombocytopenic purpura', 'TTP_COD'),\n ('thrombotic thrombocytopenic purpura', 'TTP_COD'),\n ('thyroid cancer', 'C19CAN_COD'),\n ('tophaceous gout', 'CUST_ICB_OSTEOARTHRITIS'),\n ('transitional cell carcinoma', 'C19CAN_COD'),\n ('type 1 diabetes', 'DMTYPE1_COD'),\n ('type 2 diabetes', 'DMTYPE2_COD'),\n ('ulcerative colitis', 'eFI2_InflammatoryBowelDisease'),\n ('urothelial carcinoma', 'NHAEMCANMORPH_COD'),\n ('urticaria', 'XSAL_COD'),\n ('uveitis', 'CUST_ICB_VISUAL_IMPAIRMENT'),\n ('vascular disease', 'CVDINVITE_COD'),\n ('vasculitis', 'CRYOGLOBVASC_COD')\n ) AS t(Search_Term, Cluster_ID)\n),\n\nClusterCodes AS (\n SELECT\n stc.Search_Term,\n c.\"SNOMEDCode\",\n c.\"SNOMEDDescription\"\n FROM SearchTermClusters stc\n JOIN DATA_HUB.PHM.\"ClinicalCodingClusterSnomedCodes\" c\n ON stc.Cluster_ID = c.\"Cluster_ID\"\n WHERE c.\"SNOMEDCode\" IS NOT NULL\n),\n\nExplicitCodes AS (\n SELECT Search_Term, SNOMEDCode, SNOMEDDescription FROM (VALUES\n ('acute coronary syndrome', '837091000000100', 'Manual mapping'),\n ('ankylosing spondylitis', '162930007', 'Manual mapping'),\n ('ankylosing spondylitis', '239805001', 'Manual mapping'),\n ('ankylosing spondylitis', '239810002', 'Manual mapping'),\n ('ankylosing spondylitis', '239811003', 'Manual mapping'),\n ('ankylosing spondylitis', '394990003', 'Manual mapping'),\n ('ankylosing spondylitis', '429712009', 'Manual mapping'),\n ('ankylosing spondylitis', '441562009', 'Manual mapping'),\n ('ankylosing spondylitis', '441680005', 'Manual mapping'),\n ('ankylosing spondylitis', '441930001', 'Manual mapping'),\n ('axial spondyloarthritis', '723116002', 'Manual mapping'),\n ('choroidal neovascularisation', '380621000000102', 'Manual mapping'),\n ('choroidal neovascularisation', '733124000', 'Manual mapping')\n ) AS t(Search_Term, SNOMEDCode, SNOMEDDescription)\n),\n\nAllIndicationCodes AS (\n SELECT Search_Term, \"SNOMEDCode\" AS SNOMEDCode, \"SNOMEDDescription\" AS SNOMEDDescription\n FROM ClusterCodes\n UNION ALL\n SELECT Search_Term, SNOMEDCode, SNOMEDDescription\n FROM ExplicitCodes\n)\n\"\"\"\n\n\ndef get_patient_indication_groups(\n patient_pseudonyms: list[str],\n connector: Optional[SnowflakeConnector] = None,\n batch_size: int = 500,\n earliest_hcd_date: Optional[str] = None,\n) -> \"pd.DataFrame\":\n \"\"\"\n Batch lookup GP diagnosis-based indication groups using Snowflake cluster query.\n\n Returns ALL matching Search_Terms per patient with code_frequency (count of\n matching SNOMED codes). This enables drug-aware indication matching where\n each drug is cross-referenced against the patient's GP diagnoses.\n\n The query:\n 1. Uses the cluster mapping CTE to get all Search_Term -> SNOMED code mappings\n 2. Joins with PrimaryCareClinicalCoding to find patients with matching codes\n 3. Groups by patient + Search_Term and counts matching codes (code_frequency)\n 4. Optionally restricts to GP codes from earliest_hcd_date onwards\n\n Args:\n patient_pseudonyms: List of PseudoNHSNoLinked values (matches PatientPseudonym in GP records)\n connector: Optional SnowflakeConnector (defaults to singleton)\n batch_size: Number of patients per Snowflake query batch (default 500)\n earliest_hcd_date: Optional ISO date string (YYYY-MM-DD). If provided, only\n counts GP codes from this date onwards. Should be MIN(Intervention Date)\n from the HCD DataFrame to restrict to the HCD data window.\n\n Returns:\n DataFrame with columns:\n - PatientPseudonym: The patient identifier (PseudoNHSNoLinked value)\n - Search_Term: The matched indication (e.g., \"rheumatoid arthritis\")\n - code_frequency: Count of matching SNOMED codes for this Search_Term\n\n Multiple rows per patient (one per matched Search_Term).\n Patients not found in results have no matching GP diagnosis.\n \"\"\"\n import pandas as pd\n\n logger.info(f\"Starting Snowflake-direct indication lookup for {len(patient_pseudonyms)} patients...\")\n if earliest_hcd_date:\n logger.info(f\" Restricting GP codes to >= {earliest_hcd_date}\")\n\n # Handle edge case: empty patient list\n if not patient_pseudonyms:\n logger.warning(\"Empty patient list provided\")\n return pd.DataFrame(columns=['PatientPseudonym', 'Search_Term', 'code_frequency'])\n\n # Check Snowflake availability\n if not SNOWFLAKE_AVAILABLE:\n logger.error(\"Snowflake connector not available - cannot lookup GP records\")\n return pd.DataFrame(columns=['PatientPseudonym', 'Search_Term', 'code_frequency'])\n\n if not is_snowflake_configured():\n logger.error(\"Snowflake not configured - cannot lookup GP records\")\n return pd.DataFrame(columns=['PatientPseudonym', 'Search_Term', 'code_frequency'])\n\n if connector is None:\n connector = get_connector()\n\n # Results list to collect all matches\n all_results: list[dict] = []\n\n # Process patients in batches\n total_patients = len(patient_pseudonyms)\n for batch_start in range(0, total_patients, batch_size):\n batch_end = min(batch_start + batch_size, total_patients)\n batch_pseudonyms = patient_pseudonyms[batch_start:batch_end]\n batch_num = batch_start // batch_size + 1\n total_batches = (total_patients + batch_size - 1) // batch_size\n\n logger.info(f\"Batch {batch_num}/{total_batches}: patients {batch_start + 1} to {batch_end}\")\n\n # Build patient IN clause placeholders\n patient_placeholders = \", \".join([\"%s\"] * len(batch_pseudonyms))\n\n # Build WHERE clause with optional date filter\n date_filter = \"\"\n if earliest_hcd_date:\n date_filter = f\"\\n AND pc.\\\"EventDateTime\\\" >= %s\"\n\n # Build the full query with cluster CTE\n # Returns ALL matching Search_Terms per patient with code_frequency\n # code_frequency = COUNT of matching SNOMED codes per Search_Term per patient\n query = f\"\"\"\n{CLUSTER_MAPPING_SQL}\nSELECT\n pc.\"PatientPseudonym\" AS \"PatientPseudonym\",\n aic.Search_Term AS \"Search_Term\",\n COUNT(*) AS \"code_frequency\"\nFROM DATA_HUB.PHM.\"PrimaryCareClinicalCoding\" pc\nINNER JOIN AllIndicationCodes aic\n ON pc.\"SNOMEDCode\" = aic.SNOMEDCode\nWHERE pc.\"PatientPseudonym\" IN ({patient_placeholders}){date_filter}\nGROUP BY pc.\"PatientPseudonym\", aic.Search_Term\n\"\"\"\n\n # Build params: patient pseudonyms + optional date\n params = list(batch_pseudonyms)\n if earliest_hcd_date:\n params.append(earliest_hcd_date)\n\n try:\n results = connector.execute_dict(query, tuple(params))\n\n for row in results:\n all_results.append({\n 'PatientPseudonym': row.get('PatientPseudonym'),\n 'Search_Term': row.get('Search_Term'),\n 'code_frequency': row.get('code_frequency', 0),\n })\n\n logger.debug(f\"Batch {batch_num}: found {len(results)} patient-indication matches\")\n\n except Exception as e:\n logger.error(f\"Error querying GP records for batch {batch_num}: {e}\")\n # Continue with other batches - partial results are better than none\n\n # Build result DataFrame\n result_df = pd.DataFrame(all_results)\n\n # Log summary statistics\n if len(result_df) > 0:\n unique_patients = result_df['PatientPseudonym'].nunique()\n total_rows = len(result_df)\n match_rate = 100 * unique_patients / total_patients\n unique_terms = result_df['Search_Term'].nunique()\n avg_indications = total_rows / unique_patients if unique_patients > 0 else 0\n logger.info(f\"Indication lookup complete:\")\n logger.info(f\" Total patients queried: {total_patients}\")\n logger.info(f\" Patients with GP match: {unique_patients} ({match_rate:.1f}%)\")\n logger.info(f\" Total patient-indication rows: {total_rows} (avg {avg_indications:.1f} per patient)\")\n logger.info(f\" Unique Search_Terms found: {unique_terms}\")\n\n # Log top Search_Terms\n top_terms = result_df['Search_Term'].value_counts().head(5)\n logger.info(f\" Top 5 indications: {dict(top_terms)}\")\n else:\n logger.info(f\"Indication lookup complete: 0 matches from {total_patients} patients\")\n\n return result_df\n\n\n# Export public API\n__all__ = [\n # Dataclasses\n \"ClusterSnomedCodes\",\n \"IndicationValidationResult\",\n \"DrugIndicationMatchRate\",\n \"DrugSnomedMapping\",\n \"DirectSnomedMatchResult\",\n \"DirectorateAssignment\",\n # Cluster-based lookup functions (existing)\n \"get_drug_clusters\",\n \"get_drug_cluster_ids\",\n \"get_cluster_snomed_codes\",\n \"patient_has_indication\",\n \"validate_indication\",\n \"get_indication_match_rate\",\n \"batch_validate_indications\",\n \"get_available_clusters\",\n # Direct SNOMED lookup functions (new)\n \"get_drug_snomed_codes\",\n \"patient_has_indication_direct\",\n # Diagnosis-based directorate assignment\n \"get_directorate_from_diagnosis\",\n # Batch lookup for indication groups\n \"batch_lookup_indication_groups\",\n # Drug-indication mapping from DimSearchTerm.csv\n \"SEARCH_TERM_MERGE_MAP\",\n \"load_drug_indication_mapping\",\n \"get_search_terms_for_drug\",\n # Snowflake-direct indication lookup (new approach)\n \"get_patient_indication_groups\",\n \"CLUSTER_MAPPING_SQL\",\n]\n","structuredPatch":[{"oldStart":1204,"oldLines":6,"newStart":1204,"newLines":175,"lines":[" return matched_terms"," "," ","+def assign_drug_indications(","+ df: \"pd.DataFrame\",","+ gp_matches_df: \"pd.DataFrame\",","+ search_term_to_fragments: dict[str, list[str]],","+) -> \"tuple[pd.DataFrame, pd.DataFrame]\":","+ \"\"\"","+ Assign drug-aware indications by cross-referencing GP diagnoses with drug mappings.","+","+ For each UPID + Drug Name pair in the HCD data:","+ 1. Look up patient's GP-matched Search_Terms (via PseudoNHSNoLinked  gp_matches_df)","+ 2. Look up which Search_Terms list this drug (via search_term_to_fragments)","+ 3. Intersect = valid indications for this drug-patient pair","+ 4. If 1 match: use it","+ 5. If multiple: pick highest code_frequency (most GP coding = most likely indication)","+ 6. If tied frequency: alphabetical Search_Term for determinism","+ 7. If 0 matches: fallback to \"{Directory} (no GP dx)\"","+","+ Modifies UPID to include indication: \"{UPID}|{search_term}\" or \"{UPID}|{Directory} (no GP dx)\".","+ This makes drugs under different indications appear as separate pathways.","+","+ Args:","+ df: HCD DataFrame with columns: UPID, Drug Name, PseudoNHSNoLinked, Directory","+ gp_matches_df: GP matches from get_patient_indication_groups() with columns:","+ PatientPseudonym, Search_Term, code_frequency","+ (multiple rows per patient, one per matched Search_Term)","+ search_term_to_fragments: From load_drug_indication_mapping()[1].","+ Maps search_term -> list of drug fragments (UPPERCASE).","+","+ Returns:","+ Tuple of (modified_df, indication_df):","+ - modified_df: Copy of df with UPID replaced by \"{UPID}|{indication}\"","+ - indication_df: DataFrame indexed by modified UPID with 'Directory' column","+ containing the Search_Term (or fallback label) for pathway hierarchy","+ \"\"\"","+ import pandas as pd","+","+ modified_df = df.copy()","+","+ # Build GP match lookup: PseudoNHSNoLinked -> {Search_Term: code_frequency}","+ gp_lookup: dict[str, dict[str, int]] = {}","+ if not gp_matches_df.empty:","+ for _, row in gp_matches_df.iterrows():","+ pseudo = row['PatientPseudonym']","+ term = row['Search_Term']","+ freq = int(row.get('code_frequency', 0))","+ if pseudo not in gp_lookup:","+ gp_lookup[pseudo] = {}","+ gp_lookup[pseudo][term] = freq","+","+ logger.info(f\"GP lookup built: {len(gp_lookup)} patients with GP matches\")","+","+ # Cache drug -> Search_Terms lookups to avoid recomputing per row","+ drug_search_terms_cache: dict[str, list[str]] = {}","+","+ def get_drug_terms(drug_name: str) -> list[str]:","+ if drug_name not in drug_search_terms_cache:","+ drug_search_terms_cache[drug_name] = get_search_terms_for_drug(","+ drug_name, search_term_to_fragments","+ )","+ return drug_search_terms_cache[drug_name]","+","+ # Process each row: determine indication for each UPID + Drug Name","+ # We work at the (UPID, Drug Name) pair level, then apply to all rows","+ # Key: (UPID, Drug Name) -> (matched_search_term_or_fallback, is_diagnosis)","+ pair_indication_cache: dict[tuple[str, str], tuple[str, bool]] = {}","+","+ # Get unique (UPID, Drug Name, PseudoNHSNoLinked, Directory) combos","+ required_cols = ['UPID', 'Drug Name', 'PseudoNHSNoLinked', 'Directory']","+ unique_pairs = modified_df[required_cols].drop_duplicates(","+ subset=['UPID', 'Drug Name']","+ )","+","+ match_count = 0","+ fallback_count = 0","+ tiebreak_count = 0","+","+ for _, pair_row in unique_pairs.iterrows():","+ upid = pair_row['UPID']","+ drug_name = pair_row['Drug Name']","+ pseudo = pair_row['PseudoNHSNoLinked']","+ directory = pair_row['Directory']","+","+ # Get Search_Terms this drug maps to","+ drug_terms = get_drug_terms(drug_name)","+","+ # Get patient's GP-matched Search_Terms","+ patient_gp_terms = gp_lookup.get(pseudo, {}) if pd.notna(pseudo) else {}","+","+ # Intersect: Search_Terms that list this drug AND patient has GP dx for","+ valid_indications = {","+ term: patient_gp_terms[term]","+ for term in drug_terms","+ if term in patient_gp_terms","+ }","+","+ if len(valid_indications) == 1:","+ matched_term = next(iter(valid_indications))","+ pair_indication_cache[(upid, drug_name)] = (matched_term, True)","+ match_count += 1","+","+ elif len(valid_indications) > 1:","+ # Tiebreaker: highest code_frequency, then alphabetical","+ sorted_terms = sorted(","+ valid_indications.items(),","+ key=lambda x: (-x[1], x[0]),","+ )","+ matched_term = sorted_terms[0][0]","+ pair_indication_cache[(upid, drug_name)] = (matched_term, True)","+ match_count += 1","+ tiebreak_count += 1","+","+ else:","+ # No intersection: fallback to directory","+ if pd.notna(directory):","+ fallback_label = f\"{directory} (no GP dx)\"","+ else:","+ fallback_label = \"UNKNOWN (no GP dx)\"","+ pair_indication_cache[(upid, drug_name)] = (fallback_label, False)","+ fallback_count += 1","+","+ total_pairs = len(unique_pairs)","+ logger.info(f\"Drug-indication matching complete:\")","+ logger.info(f\" Total UPID-Drug pairs: {total_pairs}\")","+ logger.info(f\" Matched (GP dx + drug mapping): {match_count} ({100*match_count/total_pairs:.1f}%)\" if total_pairs > 0 else f\" Matched: 0\")","+ logger.info(f\" Tiebreaker used: {tiebreak_count}\")","+ logger.info(f\" Fallback (no match): {fallback_count} ({100*fallback_count/total_pairs:.1f}%)\" if total_pairs > 0 else f\" Fallback: 0\")","+","+ # Apply modified UPIDs to all rows","+ # Build vectorized lookup: original UPID + Drug Name -> modified UPID","+ def build_modified_upid(row: \"pd.Series\") -> str:","+ upid = row['UPID']","+ drug_name = row['Drug Name']","+ key = (upid, drug_name)","+ if key in pair_indication_cache:","+ indication, _ = pair_indication_cache[key]","+ return f\"{upid}|{indication}\"","+ # Shouldn't happen, but fallback","+ return f\"{upid}|UNKNOWN (no GP dx)\"","+","+ modified_df['UPID'] = modified_df.apply(build_modified_upid, axis=1)","+","+ # Build indication_df: modified UPID -> Search_Term/fallback label","+ # This maps each unique modified UPID to its indication for the pathway hierarchy","+ indication_records: list[dict[str, str]] = []","+ seen_upids: set[str] = set()","+","+ for (original_upid, drug_name), (indication, is_diagnosis) in pair_indication_cache.items():","+ modified_upid = f\"{original_upid}|{indication}\"","+ if modified_upid not in seen_upids:","+ indication_records.append({","+ 'UPID': modified_upid,","+ 'Directory': indication,","+ })","+ seen_upids.add(modified_upid)","+","+ indication_df = pd.DataFrame(indication_records)","+ if not indication_df.empty:","+ indication_df = indication_df.set_index('UPID')","+","+ logger.info(f\" Unique modified UPIDs: {len(indication_df)}\")","+","+ # Log top indications","+ if not indication_df.empty:","+ top_terms = indication_df['Directory'].value_counts().head(5)","+ logger.info(f\" Top 5 indications: {dict(top_terms)}\")","+","+ return modified_df, indication_df","+","+"," # === NEW APPROACH: Query Snowflake directly using cluster CTE ==="," "," # The cluster query mapping (embedded from snomed_indication_mapping_query.sql)"]}],"userModified":false,"replaceAll":false}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01LynK621bSTpdnJ3nPMdTMj","type":"message","role":"assistant","content":[{"type":"text","text":"Now I need to update the `__all__` exports to include `assign_drug_indications`."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":2489,"cache_read_input_tokens":118570,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":2489},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"c4326d49-e7db-4967-be5d-79a796eea31c"}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01LynK621bSTpdnJ3nPMdTMj","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01P3HnsMPAd3tspRPjJarwiD","name":"Read","input":{"file_path":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\data_processing\\diagnosis_lookup.py","offset":1680,"limit":50}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":2489,"cache_read_input_tokens":118570,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":2489},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"43792b26-9624-408b-8f73-6126610238ac"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01P3HnsMPAd3tspRPjJarwiD","type":"tool_result","content":" 1680\n 1681 except Exception as e:\n 1682 logger.error(f\"Error querying GP records for batch {batch_num}: {e}\")\n 1683 # Continue with other batches - partial results are better than none\n 1684\n 1685 # Build result DataFrame\n 1686 result_df = pd.DataFrame(all_results)\n 1687\n 1688 # Log summary statistics\n 1689 if len(result_df) > 0:\n 1690 unique_patients = result_df['PatientPseudonym'].nunique()\n 1691 total_rows = len(result_df)\n 1692 match_rate = 100 * unique_patients / total_patients\n 1693 unique_terms = result_df['Search_Term'].nunique()\n 1694 avg_indications = total_rows / unique_patients if unique_patients > 0 else 0\n 1695 logger.info(f\"Indication lookup complete:\")\n 1696 logger.info(f\" Total patients queried: {total_patients}\")\n 1697 logger.info(f\" Patients with GP match: {unique_patients} ({match_rate:.1f}%)\")\n 1698 logger.info(f\" Total patient-indication rows: {total_rows} (avg {avg_indications:.1f} per patient)\")\n 1699 logger.info(f\" Unique Search_Terms found: {unique_terms}\")\n 1700\n 1701 # Log top Search_Terms\n 1702 top_terms = result_df['Search_Term'].value_counts().head(5)\n 1703 logger.info(f\" Top 5 indications: {dict(top_terms)}\")\n 1704 else:\n 1705 logger.info(f\"Indication lookup complete: 0 matches from {total_patients} patients\")\n 1706\n 1707 return result_df\n 1708\n 1709\n 1710# Export public API\n 1711__all__ = [\n 1712 # Dataclasses\n 1713 \"ClusterSnomedCodes\",\n 1714 \"IndicationValidationResult\",\n 1715 \"DrugIndicationMatchRate\",\n 1716 \"DrugSnomedMapping\",\n 1717 \"DirectSnomedMatchResult\",\n 1718 \"DirectorateAssignment\",\n 1719 # Cluster-based lookup functions (existing)\n 1720 \"get_drug_clusters\",\n 1721 \"get_drug_cluster_ids\",\n 1722 \"get_cluster_snomed_codes\",\n 1723 \"patient_has_indication\",\n 1724 \"validate_indication\",\n 1725 \"get_indication_match_rate\",\n 1726 \"batch_validate_indications\",\n 1727 \"get_available_clusters\",\n 1728 # Direct SNOMED lookup functions (new)\n 1729 \"get_drug_snomed_codes\",\n\n\nWhenever 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.\n\n"}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"81cd2c30-66ca-4ea6-b1a6-7e75d001e380","tool_use_result":{"type":"text","file":{"filePath":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\data_processing\\diagnosis_lookup.py","content":"\n except Exception as e:\n logger.error(f\"Error querying GP records for batch {batch_num}: {e}\")\n # Continue with other batches - partial results are better than none\n\n # Build result DataFrame\n result_df = pd.DataFrame(all_results)\n\n # Log summary statistics\n if len(result_df) > 0:\n unique_patients = result_df['PatientPseudonym'].nunique()\n total_rows = len(result_df)\n match_rate = 100 * unique_patients / total_patients\n unique_terms = result_df['Search_Term'].nunique()\n avg_indications = total_rows / unique_patients if unique_patients > 0 else 0\n logger.info(f\"Indication lookup complete:\")\n logger.info(f\" Total patients queried: {total_patients}\")\n logger.info(f\" Patients with GP match: {unique_patients} ({match_rate:.1f}%)\")\n logger.info(f\" Total patient-indication rows: {total_rows} (avg {avg_indications:.1f} per patient)\")\n logger.info(f\" Unique Search_Terms found: {unique_terms}\")\n\n # Log top Search_Terms\n top_terms = result_df['Search_Term'].value_counts().head(5)\n logger.info(f\" Top 5 indications: {dict(top_terms)}\")\n else:\n logger.info(f\"Indication lookup complete: 0 matches from {total_patients} patients\")\n\n return result_df\n\n\n# Export public API\n__all__ = [\n # Dataclasses\n \"ClusterSnomedCodes\",\n \"IndicationValidationResult\",\n \"DrugIndicationMatchRate\",\n \"DrugSnomedMapping\",\n \"DirectSnomedMatchResult\",\n \"DirectorateAssignment\",\n # Cluster-based lookup functions (existing)\n \"get_drug_clusters\",\n \"get_drug_cluster_ids\",\n \"get_cluster_snomed_codes\",\n \"patient_has_indication\",\n \"validate_indication\",\n \"get_indication_match_rate\",\n \"batch_validate_indications\",\n \"get_available_clusters\",\n # Direct SNOMED lookup functions (new)\n \"get_drug_snomed_codes\",","numLines":50,"startLine":1680,"totalLines":1743}}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_012fgNyzz6xvNiaAmHb9c3ns","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01NWLps6SFKBgw3hMjy9K8Wu","name":"Read","input":{"file_path":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\data_processing\\diagnosis_lookup.py","offset":1730,"limit":20}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":1009,"cache_read_input_tokens":121059,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":1009},"output_tokens":25,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"f2cbf03e-c42d-4652-bcc5-4ff80f531953"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01NWLps6SFKBgw3hMjy9K8Wu","type":"tool_result","content":" 1730 \"patient_has_indication_direct\",\n 1731 # Diagnosis-based directorate assignment\n 1732 \"get_directorate_from_diagnosis\",\n 1733 # Batch lookup for indication groups\n 1734 \"batch_lookup_indication_groups\",\n 1735 # Drug-indication mapping from DimSearchTerm.csv\n 1736 \"SEARCH_TERM_MERGE_MAP\",\n 1737 \"load_drug_indication_mapping\",\n 1738 \"get_search_terms_for_drug\",\n 1739 # Snowflake-direct indication lookup (new approach)\n 1740 \"get_patient_indication_groups\",\n 1741 \"CLUSTER_MAPPING_SQL\",\n 1742]\n 1743\n\n\nWhenever 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.\n\n"}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"6112129f-299e-478e-916b-54eebc3f7572","tool_use_result":{"type":"text","file":{"filePath":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\data_processing\\diagnosis_lookup.py","content":" \"patient_has_indication_direct\",\n # Diagnosis-based directorate assignment\n \"get_directorate_from_diagnosis\",\n # Batch lookup for indication groups\n \"batch_lookup_indication_groups\",\n # Drug-indication mapping from DimSearchTerm.csv\n \"SEARCH_TERM_MERGE_MAP\",\n \"load_drug_indication_mapping\",\n \"get_search_terms_for_drug\",\n # Snowflake-direct indication lookup (new approach)\n \"get_patient_indication_groups\",\n \"CLUSTER_MAPPING_SQL\",\n]\n","numLines":14,"startLine":1730,"totalLines":1743}}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01HpJf369FPd2nn1MWFnhkNS","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01BpUHu7FzeRR8mbqm26MGow","name":"Edit","input":{"replace_all":false,"file_path":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\data_processing\\diagnosis_lookup.py","old_string":" # Drug-indication mapping from DimSearchTerm.csv\n \"SEARCH_TERM_MERGE_MAP\",\n \"load_drug_indication_mapping\",\n \"get_search_terms_for_drug\",\n # Snowflake-direct indication lookup (new approach)","new_string":" # Drug-indication mapping from DimSearchTerm.csv\n \"SEARCH_TERM_MERGE_MAP\",\n \"load_drug_indication_mapping\",\n \"get_search_terms_for_drug\",\n # Drug-aware indication assignment\n \"assign_drug_indications\",\n # Snowflake-direct indication lookup (new approach)"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":408,"cache_read_input_tokens":122068,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":408},"output_tokens":25,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"66a7faca-f0af-46a5-9ef7-d11a9ab83a16"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01BpUHu7FzeRR8mbqm26MGow","type":"tool_result","content":"The file C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\data_processing\\diagnosis_lookup.py has been updated successfully."}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"9bb0f813-c1fb-484f-9dc0-48b3f4757036","tool_use_result":{"filePath":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\data_processing\\diagnosis_lookup.py","oldString":" # Drug-indication mapping from DimSearchTerm.csv\n \"SEARCH_TERM_MERGE_MAP\",\n \"load_drug_indication_mapping\",\n \"get_search_terms_for_drug\",\n # Snowflake-direct indication lookup (new approach)","newString":" # Drug-indication mapping from DimSearchTerm.csv\n \"SEARCH_TERM_MERGE_MAP\",\n \"load_drug_indication_mapping\",\n \"get_search_terms_for_drug\",\n # Drug-aware indication assignment\n \"assign_drug_indications\",\n # Snowflake-direct indication lookup (new approach)","originalFile":"\"\"\"\nDiagnosis lookup module for NHS Patient Pathway Analysis.\n\nProvides functions to validate patient indications by checking GP diagnosis records\nagainst SNOMED cluster codes. Uses the drug-to-cluster mapping from\ndrug_indication_clusters.csv and queries Snowflake for SNOMED codes and GP records.\n\nKey workflow:\n1. Get drug's valid indication clusters from local mapping\n2. Get all SNOMED codes for those clusters from Snowflake\n3. Check if patient has any of those SNOMED codes in GP records\n4. Report indication validation status\n\nIMPORTANT: HCD activity data indication codes are UNRELIABLE. This module uses\nGP/Primary Care data (PrimaryCareClinicalCoding) as the authoritative source.\n\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom datetime import date, datetime\nfrom pathlib import Path\nfrom typing import Optional, Callable, Any, cast, TYPE_CHECKING\nimport csv\n\nif TYPE_CHECKING:\n import pandas as pd\n\nfrom core.logging_config import get_logger\nfrom data_processing.database import DatabaseManager, default_db_manager\nfrom data_processing.snowflake_connector import (\n SnowflakeConnector,\n get_connector,\n is_snowflake_available,\n is_snowflake_configured,\n SNOWFLAKE_AVAILABLE,\n)\nfrom data_processing.cache import get_cache, is_cache_enabled\n\nlogger = get_logger(__name__)\n\n\n@dataclass\nclass ClusterSnomedCodes:\n \"\"\"SNOMED codes for a clinical coding cluster.\"\"\"\n cluster_id: str\n cluster_description: str\n snomed_codes: list[str] = field(default_factory=list)\n snomed_descriptions: dict[str, str] = field(default_factory=dict)\n\n @property\n def code_count(self) -> int:\n return len(self.snomed_codes)\n\n\n@dataclass\nclass IndicationValidationResult:\n \"\"\"Result of validating a patient's indication for a drug.\"\"\"\n patient_pseudonym: str\n drug_name: str\n has_valid_indication: bool\n matched_cluster_id: Optional[str] = None\n matched_snomed_code: Optional[str] = None\n matched_snomed_description: Optional[str] = None\n checked_clusters: list[str] = field(default_factory=list)\n total_codes_checked: int = 0\n source: str = \"GP_SNOMED\" # GP_SNOMED | NONE\n error_message: Optional[str] = None\n\n\n@dataclass\nclass DrugIndicationMatchRate:\n \"\"\"Match rate statistics for a drug's indication validation.\"\"\"\n drug_name: str\n total_patients: int\n patients_with_indication: int\n patients_without_indication: int\n match_rate: float # 0.0 to 1.0\n clusters_checked: list[str] = field(default_factory=list)\n sample_unmatched: list[str] = field(default_factory=list) # Sample patient IDs\n\n\n@dataclass\nclass DrugSnomedMapping:\n \"\"\"SNOMED code mapping for a drug from ref_drug_snomed_mapping.\"\"\"\n snomed_code: str\n snomed_description: str\n search_term: str\n primary_directorate: str\n indication: str = \"\"\n ta_id: str = \"\"\n\n\n@dataclass\nclass DirectSnomedMatchResult:\n \"\"\"Result of direct SNOMED code lookup in GP records.\"\"\"\n patient_pseudonym: str\n matched: bool\n snomed_code: Optional[str] = None\n snomed_description: Optional[str] = None\n search_term: Optional[str] = None\n primary_directorate: Optional[str] = None\n event_date: Optional[datetime] = None\n source: str = \"DIRECT_SNOMED\" # DIRECT_SNOMED | NONE\n\n\n@dataclass\nclass DirectorateAssignment:\n \"\"\"Result of directorate assignment for a patient-drug combination.\"\"\"\n upid: str\n drug_name: str\n directorate: Optional[str]\n search_term: Optional[str] = None\n source: str = \"FALLBACK\" # DIAGNOSIS | FALLBACK\n snomed_code: Optional[str] = None\n event_date: Optional[datetime] = None\n\n\ndef get_drug_clusters(\n drug_name: str,\n db_manager: Optional[DatabaseManager] = None\n) -> list[dict]:\n \"\"\"\n Get all SNOMED cluster mappings for a drug from local SQLite.\n\n Args:\n drug_name: Drug name to look up (case-insensitive)\n db_manager: Optional DatabaseManager (defaults to default_db_manager)\n\n Returns:\n List of dicts with keys: drug_name, indication, cluster_id,\n cluster_description, nice_ta_reference\n \"\"\"\n if db_manager is None:\n db_manager = default_db_manager\n\n query = \"\"\"\n SELECT drug_name, indication, cluster_id, cluster_description, nice_ta_reference\n FROM ref_drug_indication_clusters\n WHERE UPPER(drug_name) = UPPER(?)\n ORDER BY indication, cluster_id\n \"\"\"\n\n try:\n with db_manager.get_connection() as conn:\n cursor = conn.execute(query, (drug_name,))\n rows = cursor.fetchall()\n\n results = []\n for row in rows:\n results.append({\n \"drug_name\": row[\"drug_name\"],\n \"indication\": row[\"indication\"],\n \"cluster_id\": row[\"cluster_id\"],\n \"cluster_description\": row[\"cluster_description\"],\n \"nice_ta_reference\": row[\"nice_ta_reference\"],\n })\n\n logger.debug(f\"Found {len(results)} cluster mappings for drug '{drug_name}'\")\n return results\n\n except Exception as e:\n logger.error(f\"Error getting clusters for drug '{drug_name}': {e}\")\n return []\n\n\ndef get_drug_cluster_ids(\n drug_name: str,\n db_manager: Optional[DatabaseManager] = None\n) -> list[str]:\n \"\"\"\n Get unique cluster IDs for a drug.\n\n Args:\n drug_name: Drug name to look up\n db_manager: Optional DatabaseManager\n\n Returns:\n List of unique cluster IDs\n \"\"\"\n clusters = get_drug_clusters(drug_name, db_manager)\n return list(set(c[\"cluster_id\"] for c in clusters))\n\n\ndef get_drug_snomed_codes(\n drug_name: str,\n db_manager: Optional[DatabaseManager] = None\n) -> list[DrugSnomedMapping]:\n \"\"\"\n Get all SNOMED codes for a drug from local ref_drug_snomed_mapping table.\n\n This uses the enriched mapping CSV data loaded into SQLite, which provides\n direct SNOMED-to-drug mappings with Search_Term and PrimaryDirectorate.\n\n Args:\n drug_name: Drug name to look up (case-insensitive, matches cleaned_drug_name)\n db_manager: Optional DatabaseManager (defaults to default_db_manager)\n\n Returns:\n List of DrugSnomedMapping with snomed_code, snomed_description,\n search_term, primary_directorate, indication, ta_id\n \"\"\"\n if db_manager is None:\n db_manager = default_db_manager\n\n query = \"\"\"\n SELECT DISTINCT\n snomed_code,\n snomed_description,\n search_term,\n primary_directorate,\n indication,\n ta_id\n FROM ref_drug_snomed_mapping\n WHERE UPPER(cleaned_drug_name) = UPPER(?)\n OR UPPER(drug_name) = UPPER(?)\n ORDER BY search_term, snomed_code\n \"\"\"\n\n try:\n with db_manager.get_connection() as conn:\n cursor = conn.execute(query, (drug_name, drug_name))\n rows = cursor.fetchall()\n\n results = []\n for row in rows:\n results.append(DrugSnomedMapping(\n snomed_code=row[\"snomed_code\"],\n snomed_description=row[\"snomed_description\"] or \"\",\n search_term=row[\"search_term\"] or \"\",\n primary_directorate=row[\"primary_directorate\"] or \"\",\n indication=row[\"indication\"] or \"\",\n ta_id=row[\"ta_id\"] or \"\",\n ))\n\n logger.debug(f\"Found {len(results)} SNOMED mappings for drug '{drug_name}'\")\n return results\n\n except Exception as e:\n logger.error(f\"Error getting SNOMED codes for drug '{drug_name}': {e}\")\n return []\n\n\ndef patient_has_indication_direct(\n patient_pseudonym: str,\n drug_snomed_mappings: list[DrugSnomedMapping],\n connector: Optional[SnowflakeConnector] = None,\n before_date: Optional[date] = None,\n) -> DirectSnomedMatchResult:\n \"\"\"\n Check if patient has any of the SNOMED codes in their GP records.\n\n This is the direct SNOMED lookup - it queries PrimaryCareClinicalCoding\n for exact SNOMED code matches (not via cluster). Returns the most recent\n match by EventDateTime if multiple matches exist.\n\n Args:\n patient_pseudonym: Patient's pseudonymised NHS number\n drug_snomed_mappings: List of DrugSnomedMapping from get_drug_snomed_codes()\n connector: Optional SnowflakeConnector (defaults to singleton)\n before_date: Optional date - only check diagnoses before this date\n\n Returns:\n DirectSnomedMatchResult with match details (most recent by EventDateTime)\n \"\"\"\n result = DirectSnomedMatchResult(\n patient_pseudonym=patient_pseudonym,\n matched=False,\n source=\"NONE\",\n )\n\n if not drug_snomed_mappings:\n return result\n\n if not SNOWFLAKE_AVAILABLE:\n logger.warning(\"Snowflake connector not available\")\n return result\n\n if not is_snowflake_configured():\n logger.warning(\"Snowflake not configured - cannot check GP records\")\n return result\n\n if connector is None:\n connector = get_connector()\n\n # Build lookup dict for mapping snomed_code -> (search_term, primary_directorate, snomed_description)\n snomed_lookup = {\n m.snomed_code: (m.search_term, m.primary_directorate, m.snomed_description)\n for m in drug_snomed_mappings\n }\n\n # Get unique SNOMED codes\n snomed_codes = list(snomed_lookup.keys())\n\n # Build placeholders for SNOMED codes\n placeholders = \", \".join([\"%s\"] * len(snomed_codes))\n\n # Query to find most recent matching SNOMED code in GP records\n query = f'''\n SELECT\n \"SNOMEDCode\",\n \"EventDateTime\"\n FROM DATA_HUB.PHM.\"PrimaryCareClinicalCoding\"\n WHERE \"PatientPseudonym\" = %s\n AND \"SNOMEDCode\" IN ({placeholders})\n '''\n\n params: list = [patient_pseudonym] + snomed_codes\n\n if before_date:\n query += ' AND \"EventDateTime\" < %s'\n params.append(before_date.isoformat())\n\n query += ' ORDER BY \"EventDateTime\" DESC LIMIT 1'\n\n try:\n results = connector.execute_dict(query, tuple(params))\n\n if results:\n row = results[0]\n matched_code = row.get(\"SNOMEDCode\")\n event_dt = row.get(\"EventDateTime\")\n\n if matched_code and matched_code in snomed_lookup:\n search_term, primary_dir, snomed_desc = snomed_lookup[matched_code]\n\n return DirectSnomedMatchResult(\n patient_pseudonym=patient_pseudonym,\n matched=True,\n snomed_code=matched_code,\n snomed_description=snomed_desc,\n search_term=search_term,\n primary_directorate=primary_dir,\n event_date=event_dt,\n source=\"DIRECT_SNOMED\",\n )\n\n return result\n\n except Exception as e:\n logger.error(f\"Error checking direct SNOMED for patient '{patient_pseudonym}': {e}\")\n return result\n\n\ndef get_directorate_from_diagnosis(\n upid: str,\n drug_name: str,\n connector: Optional[SnowflakeConnector] = None,\n db_manager: Optional[DatabaseManager] = None,\n before_date: Optional[date] = None,\n) -> DirectorateAssignment:\n \"\"\"\n Get directorate assignment for a patient-drug combination using diagnosis-based lookup.\n\n This function attempts to assign a directorate based on the patient's GP records\n (direct SNOMED code matching). If no match is found, it returns a FALLBACK result\n indicating that the caller should use alternative assignment methods (e.g.,\n department_identification() from tools/data.py).\n\n Workflow:\n 1. Get all SNOMED codes for the drug from ref_drug_snomed_mapping\n 2. Query patient's GP records for matching SNOMED codes\n 3. If match found  return diagnosis-based directorate and search_term\n 4. If no match  return FALLBACK result (caller handles fallback logic)\n\n Args:\n upid: Patient's unique patient ID (Provider Code[:3] + PersonKey)\n drug_name: Drug name to look up\n connector: Optional SnowflakeConnector (defaults to singleton)\n db_manager: Optional DatabaseManager (defaults to default_db_manager)\n before_date: Optional date - only check diagnoses before this date\n\n Returns:\n DirectorateAssignment with directorate, search_term, and source\n \"\"\"\n result = DirectorateAssignment(\n upid=upid,\n drug_name=drug_name,\n directorate=None,\n source=\"FALLBACK\",\n )\n\n # Step 1: Get SNOMED codes for the drug\n drug_snomed_mappings = get_drug_snomed_codes(drug_name, db_manager)\n\n if not drug_snomed_mappings:\n logger.debug(f\"No SNOMED mappings found for drug '{drug_name}' - using fallback\")\n return result\n\n # Step 2: Check Snowflake availability\n if not SNOWFLAKE_AVAILABLE:\n logger.debug(\"Snowflake not available - using fallback\")\n return result\n\n if not is_snowflake_configured():\n logger.debug(\"Snowflake not configured - using fallback\")\n return result\n\n # Step 3: Get patient pseudonym from UPID\n # UPID format is Provider Code (3 chars) + PersonKey\n # We need to query Snowflake to get the PatientPseudonym for this PersonKey\n # However, patient_has_indication_direct expects PatientPseudonym, not UPID\n # For now, we'll use UPID as the identifier - the actual integration\n # will need to happen at the DataFrame level where we have PersonKey\n #\n # NOTE: This function will be called from the pipeline where we have\n # access to PatientPseudonym. The UPID is passed for logging/tracking.\n\n # Actually, looking at the pipeline, we need PatientPseudonym, not UPID.\n # The caller should pass the PatientPseudonym or we need to look it up.\n # For now, let's assume the caller will use this in a batch context\n # where they can map UPID -> PatientPseudonym.\n\n # Let me reconsider: the function signature takes UPID but we need\n # PatientPseudonym for Snowflake. In the pipeline context (fetch_and_transform_data),\n # we'll have the PersonKey column which IS the PatientPseudonym.\n # So UPID = ProviderCode[:3] + PersonKey, and PersonKey = PatientPseudonym.\n #\n # We can extract PatientPseudonym from UPID by removing the first 3 chars.\n patient_pseudonym = upid[3:] if len(upid) > 3 else upid\n\n # Step 4: Check patient's GP records for matching SNOMED codes\n match_result = patient_has_indication_direct(\n patient_pseudonym=patient_pseudonym,\n drug_snomed_mappings=drug_snomed_mappings,\n connector=connector,\n before_date=before_date,\n )\n\n if match_result.matched and match_result.primary_directorate:\n return DirectorateAssignment(\n upid=upid,\n drug_name=drug_name,\n directorate=match_result.primary_directorate,\n search_term=match_result.search_term,\n source=\"DIAGNOSIS\",\n snomed_code=match_result.snomed_code,\n event_date=match_result.event_date,\n )\n\n # No match found - return fallback result\n return result\n\n\ndef get_cluster_snomed_codes(\n cluster_id: str,\n connector: Optional[SnowflakeConnector] = None,\n use_cache: bool = True,\n) -> ClusterSnomedCodes:\n \"\"\"\n Get all SNOMED codes for a cluster from Snowflake.\n\n Queries the ClinicalCodingClusterSnomedCodes table to get all SNOMED codes\n that belong to the specified cluster.\n\n Args:\n cluster_id: Cluster ID to look up (e.g., 'RARTH_COD', 'PSORIASIS_COD')\n connector: Optional SnowflakeConnector (defaults to singleton)\n use_cache: Whether to use cached results (default True)\n\n Returns:\n ClusterSnomedCodes with list of SNOMED codes and descriptions\n \"\"\"\n if not SNOWFLAKE_AVAILABLE:\n logger.warning(\"Snowflake connector not available\")\n return ClusterSnomedCodes(cluster_id=cluster_id, cluster_description=\"\")\n\n if not is_snowflake_configured():\n logger.warning(\"Snowflake not configured - cannot get cluster codes\")\n return ClusterSnomedCodes(cluster_id=cluster_id, cluster_description=\"\")\n\n # Check cache first\n cache_key = f\"cluster_snomed_{cluster_id}\"\n if use_cache and is_cache_enabled():\n cache = get_cache()\n cached = cache.get(cache_key)\n if cached is not None and len(cached) > 0:\n logger.debug(f\"Using cached SNOMED codes for cluster '{cluster_id}'\")\n cached_dict = cached[0] # First element is our data dict\n return ClusterSnomedCodes(\n cluster_id=cluster_id,\n cluster_description=str(cached_dict.get(\"description\", \"\")),\n snomed_codes=list(cached_dict.get(\"codes\", [])),\n snomed_descriptions=dict(cached_dict.get(\"descriptions\", {})),\n )\n\n if connector is None:\n connector = get_connector()\n\n query = '''\n SELECT DISTINCT\n \"Cluster_ID\",\n \"Cluster_Description\",\n \"SNOMEDCode\",\n \"SNOMEDDescription\"\n FROM DATA_HUB.PHM.\"ClinicalCodingClusterSnomedCodes\"\n WHERE \"Cluster_ID\" = %s\n ORDER BY \"SNOMEDCode\"\n '''\n\n try:\n results = connector.execute_dict(query, (cluster_id,))\n\n if not results:\n logger.warning(f\"No SNOMED codes found for cluster '{cluster_id}'\")\n return ClusterSnomedCodes(cluster_id=cluster_id, cluster_description=\"\")\n\n codes = []\n descriptions = {}\n description = results[0].get(\"Cluster_Description\", \"\") if results else \"\"\n\n for row in results:\n code = row.get(\"SNOMEDCode\")\n if code:\n codes.append(code)\n descriptions[code] = row.get(\"SNOMEDDescription\", \"\")\n\n logger.info(f\"Found {len(codes)} SNOMED codes for cluster '{cluster_id}'\")\n\n # Cache the results (using query-based cache with fake params)\n if use_cache and is_cache_enabled():\n cache = get_cache()\n cache_data = [{\n \"description\": description,\n \"codes\": codes,\n \"descriptions\": descriptions,\n }]\n cache.set(cache_key, None, cache_data) # type: ignore[arg-type]\n\n return ClusterSnomedCodes(\n cluster_id=cluster_id,\n cluster_description=description,\n snomed_codes=codes,\n snomed_descriptions=descriptions,\n )\n\n except Exception as e:\n logger.error(f\"Error getting SNOMED codes for cluster '{cluster_id}': {e}\")\n return ClusterSnomedCodes(cluster_id=cluster_id, cluster_description=\"\")\n\n\ndef patient_has_indication(\n patient_pseudonym: str,\n cluster_ids: list[str],\n connector: Optional[SnowflakeConnector] = None,\n before_date: Optional[date] = None,\n) -> tuple[bool, Optional[str], Optional[str], Optional[str]]:\n \"\"\"\n Check if a patient has any SNOMED codes from the specified clusters in GP records.\n\n Args:\n patient_pseudonym: Patient's pseudonymised NHS number\n cluster_ids: List of cluster IDs to check against\n connector: Optional SnowflakeConnector\n before_date: Optional date - only check diagnoses before this date\n\n Returns:\n Tuple of (has_indication, matched_cluster_id, matched_snomed_code, matched_description)\n \"\"\"\n if not SNOWFLAKE_AVAILABLE or not is_snowflake_configured():\n return False, None, None, None\n\n if not cluster_ids:\n return False, None, None, None\n\n if connector is None:\n connector = get_connector()\n\n # Build placeholders for cluster IDs\n placeholders = \", \".join([\"%s\"] * len(cluster_ids))\n\n # Query to check if patient has any matching SNOMED code\n query = f'''\n SELECT\n pc.\"SNOMEDCode\",\n cc.\"Cluster_ID\",\n cc.\"SNOMEDDescription\"\n FROM DATA_HUB.PHM.\"PrimaryCareClinicalCoding\" pc\n INNER JOIN DATA_HUB.PHM.\"ClinicalCodingClusterSnomedCodes\" cc\n ON pc.\"SNOMEDCode\" = cc.\"SNOMEDCode\"\n WHERE pc.\"PatientPseudonym\" = %s\n AND cc.\"Cluster_ID\" IN ({placeholders})\n '''\n\n params = [patient_pseudonym] + cluster_ids\n\n if before_date:\n query += ' AND pc.\"EventDateTime\" < %s'\n params.append(before_date.isoformat())\n\n query += ' LIMIT 1'\n\n try:\n results = connector.execute_dict(query, tuple(params))\n\n if results:\n row = results[0]\n return (\n True,\n row.get(\"Cluster_ID\"),\n row.get(\"SNOMEDCode\"),\n row.get(\"SNOMEDDescription\"),\n )\n\n return False, None, None, None\n\n except Exception as e:\n logger.error(f\"Error checking indication for patient '{patient_pseudonym}': {e}\")\n return False, None, None, None\n\n\ndef validate_indication(\n patient_pseudonym: str,\n drug_name: str,\n connector: Optional[SnowflakeConnector] = None,\n db_manager: Optional[DatabaseManager] = None,\n before_date: Optional[date] = None,\n) -> IndicationValidationResult:\n \"\"\"\n Validate that a patient has an appropriate indication for a drug.\n\n Full validation workflow:\n 1. Get drug's valid indication clusters from local mapping\n 2. Check if patient has any matching SNOMED codes in GP records\n 3. Return detailed validation result\n\n Args:\n patient_pseudonym: Patient's pseudonymised NHS number\n drug_name: Drug name to validate indication for\n connector: Optional SnowflakeConnector\n db_manager: Optional DatabaseManager\n before_date: Optional date - only check diagnoses before this date\n\n Returns:\n IndicationValidationResult with validation details\n \"\"\"\n result = IndicationValidationResult(\n patient_pseudonym=patient_pseudonym,\n drug_name=drug_name,\n has_valid_indication=False,\n )\n\n # Step 1: Get drug's cluster mappings\n cluster_ids = get_drug_cluster_ids(drug_name, db_manager)\n\n if not cluster_ids:\n result.error_message = f\"No cluster mappings found for drug '{drug_name}'\"\n result.source = \"NONE\"\n return result\n\n result.checked_clusters = cluster_ids\n\n # Step 2: Check Snowflake availability\n if not SNOWFLAKE_AVAILABLE:\n result.error_message = \"Snowflake connector not installed\"\n result.source = \"NONE\"\n return result\n\n if not is_snowflake_configured():\n result.error_message = \"Snowflake not configured\"\n result.source = \"NONE\"\n return result\n\n # Step 3: Check patient GP records\n has_indication, matched_cluster, matched_code, matched_desc = patient_has_indication(\n patient_pseudonym=patient_pseudonym,\n cluster_ids=cluster_ids,\n connector=connector,\n before_date=before_date,\n )\n\n result.has_valid_indication = has_indication\n result.matched_cluster_id = matched_cluster\n result.matched_snomed_code = matched_code\n result.matched_snomed_description = matched_desc\n result.source = \"GP_SNOMED\" if has_indication else \"NONE\"\n\n return result\n\n\ndef get_indication_match_rate(\n drug_name: str,\n patient_pseudonyms: list[str],\n connector: Optional[SnowflakeConnector] = None,\n db_manager: Optional[DatabaseManager] = None,\n sample_unmatched_count: int = 10,\n) -> DrugIndicationMatchRate:\n \"\"\"\n Calculate indication match rate for a drug across a list of patients.\n\n Args:\n drug_name: Drug name to check\n patient_pseudonyms: List of patient pseudonymised NHS numbers\n connector: Optional SnowflakeConnector\n db_manager: Optional DatabaseManager\n sample_unmatched_count: Number of unmatched patient IDs to include in sample\n\n Returns:\n DrugIndicationMatchRate with match statistics\n \"\"\"\n if connector is None and SNOWFLAKE_AVAILABLE and is_snowflake_configured():\n connector = get_connector()\n\n cluster_ids = get_drug_cluster_ids(drug_name, db_manager)\n\n total = len(patient_pseudonyms)\n matched = 0\n unmatched = 0\n sample_unmatched: list[str] = []\n\n if not cluster_ids:\n logger.warning(f\"No cluster mappings for drug '{drug_name}' - all patients will be unmatched\")\n return DrugIndicationMatchRate(\n drug_name=drug_name,\n total_patients=total,\n patients_with_indication=0,\n patients_without_indication=total,\n match_rate=0.0,\n clusters_checked=[],\n sample_unmatched=patient_pseudonyms[:sample_unmatched_count],\n )\n\n for i, pseudonym in enumerate(patient_pseudonyms):\n if i > 0 and i % 100 == 0:\n logger.info(f\"Validating indications: {i}/{total} ({100*i/total:.1f}%)\")\n\n has_indication, _, _, _ = patient_has_indication(\n patient_pseudonym=pseudonym,\n cluster_ids=cluster_ids,\n connector=connector,\n )\n\n if has_indication:\n matched += 1\n else:\n unmatched += 1\n if len(sample_unmatched) < sample_unmatched_count:\n sample_unmatched.append(pseudonym)\n\n match_rate = matched / total if total > 0 else 0.0\n\n logger.info(f\"Indication match rate for '{drug_name}': {100*match_rate:.1f}% ({matched}/{total})\")\n\n return DrugIndicationMatchRate(\n drug_name=drug_name,\n total_patients=total,\n patients_with_indication=matched,\n patients_without_indication=unmatched,\n match_rate=match_rate,\n clusters_checked=cluster_ids,\n sample_unmatched=sample_unmatched,\n )\n\n\ndef batch_validate_indications(\n patient_drug_pairs: list[tuple[str, str]],\n connector: Optional[SnowflakeConnector] = None,\n db_manager: Optional[DatabaseManager] = None,\n progress_callback: Optional[Callable[[int, int], None]] = None,\n) -> list[IndicationValidationResult]:\n \"\"\"\n Validate indications for multiple patient-drug pairs efficiently.\n\n Args:\n patient_drug_pairs: List of (patient_pseudonym, drug_name) tuples\n connector: Optional SnowflakeConnector\n db_manager: Optional DatabaseManager\n progress_callback: Optional callback(current, total) for progress updates\n\n Returns:\n List of IndicationValidationResult for each pair\n \"\"\"\n results = []\n total = len(patient_drug_pairs)\n\n # Cache cluster lookups by drug\n drug_clusters_cache = {}\n\n for i, (pseudonym, drug_name) in enumerate(patient_drug_pairs):\n if progress_callback:\n progress_callback(i + 1, total)\n\n # Get clusters from cache or lookup\n drug_upper = drug_name.upper()\n if drug_upper not in drug_clusters_cache:\n drug_clusters_cache[drug_upper] = get_drug_cluster_ids(drug_name, db_manager)\n\n cluster_ids = drug_clusters_cache[drug_upper]\n\n if not cluster_ids:\n results.append(IndicationValidationResult(\n patient_pseudonym=pseudonym,\n drug_name=drug_name,\n has_valid_indication=False,\n source=\"NONE\",\n error_message=f\"No cluster mappings for drug '{drug_name}'\",\n ))\n continue\n\n # Check patient indication\n has_indication, matched_cluster, matched_code, matched_desc = patient_has_indication(\n patient_pseudonym=pseudonym,\n cluster_ids=cluster_ids,\n connector=connector,\n )\n\n results.append(IndicationValidationResult(\n patient_pseudonym=pseudonym,\n drug_name=drug_name,\n has_valid_indication=has_indication,\n matched_cluster_id=matched_cluster,\n matched_snomed_code=matched_code,\n matched_snomed_description=matched_desc,\n checked_clusters=cluster_ids,\n source=\"GP_SNOMED\" if has_indication else \"NONE\",\n ))\n\n matched_count = sum(1 for r in results if r.has_valid_indication)\n logger.info(f\"Batch validation complete: {matched_count}/{total} ({100*matched_count/total:.1f}%) with valid indications\")\n\n return results\n\n\ndef get_available_clusters(\n connector: Optional[SnowflakeConnector] = None,\n) -> list[dict]:\n \"\"\"\n Get list of all available SNOMED clusters from Snowflake.\n\n Returns:\n List of dicts with cluster_id, cluster_description, code_count\n \"\"\"\n if not SNOWFLAKE_AVAILABLE or not is_snowflake_configured():\n logger.warning(\"Snowflake not available - cannot list clusters\")\n return []\n\n if connector is None:\n connector = get_connector()\n\n query = '''\n SELECT\n \"Cluster_ID\",\n \"Cluster_Description\",\n COUNT(DISTINCT \"SNOMEDCode\") as code_count\n FROM DATA_HUB.PHM.\"ClinicalCodingClusterSnomedCodes\"\n GROUP BY \"Cluster_ID\", \"Cluster_Description\"\n ORDER BY \"Cluster_ID\"\n '''\n\n try:\n results = connector.execute_dict(query)\n\n clusters = []\n for row in results:\n clusters.append({\n \"cluster_id\": row.get(\"Cluster_ID\"),\n \"cluster_description\": row.get(\"Cluster_Description\"),\n \"code_count\": row.get(\"code_count\", 0),\n })\n\n logger.info(f\"Found {len(clusters)} available SNOMED clusters\")\n return clusters\n\n except Exception as e:\n logger.error(f\"Error getting available clusters: {e}\")\n return []\n\n\ndef batch_lookup_indication_groups(\n df: \"pd.DataFrame\",\n connector: Optional[SnowflakeConnector] = None,\n db_manager: Optional[DatabaseManager] = None,\n batch_size: int = 500,\n) -> \"pd.DataFrame\":\n \"\"\"\n Batch lookup GP diagnosis-based indication groups for a DataFrame of patients.\n\n This is the efficient batch version of get_directorate_from_diagnosis().\n Instead of querying Snowflake per patient, it batches the lookups for performance.\n\n Strategy:\n 1. Get all unique (PersonKey, Drug Name) pairs from DataFrame\n 2. For each unique drug, get all SNOMED codes from local SQLite\n 3. Build batched Snowflake queries to check GP records\n 4. Return indication_df mapping UPID  Indication_Group\n\n For unmatched patients, Indication_Group will be their Directory (with suffix).\n\n Args:\n df: DataFrame with columns: UPID, Drug Name, Directory, PersonKey\n connector: Optional SnowflakeConnector (defaults to singleton)\n db_manager: Optional DatabaseManager (defaults to default_db_manager)\n batch_size: Number of patients per Snowflake query batch\n\n Returns:\n DataFrame with columns: UPID, Indication_Group, Source\n - Indication_Group: Search_Term (if matched) or \"Directory (no GP dx)\" (if not)\n - Source: \"DIAGNOSIS\" or \"FALLBACK\"\n \"\"\"\n import pandas as pd\n\n if db_manager is None:\n db_manager = default_db_manager\n\n logger.info(f\"Starting batch indication lookup for {len(df)} records...\")\n\n # Step 1: Get unique (UPID, Drug Name, PseudoNHSNoLinked, Directory) combinations\n # We need PseudoNHSNoLinked to query Snowflake - this matches PatientPseudonym in GP records\n # Note: PersonKey is LocalPatientID which is provider-specific and does NOT match GP records\n if 'PseudoNHSNoLinked' not in df.columns:\n logger.error(\"DataFrame missing 'PseudoNHSNoLinked' column - cannot lookup GP records\")\n # Return fallback for all patients\n result_df = df[['UPID', 'Directory']].drop_duplicates().copy()\n result_df['Indication_Group'] = result_df['Directory'] + \" (no GP dx)\"\n result_df['Source'] = \"FALLBACK\"\n return result_df[['UPID', 'Indication_Group', 'Source']]\n\n # Get unique patient-drug combinations (we need one lookup per patient-drug pair)\n unique_pairs = df[['UPID', 'Drug Name', 'PseudoNHSNoLinked', 'Directory']].drop_duplicates()\n logger.info(f\"Found {len(unique_pairs)} unique patient-drug combinations\")\n\n # Step 2: Get all unique drugs and their SNOMED codes\n unique_drugs = unique_pairs['Drug Name'].unique()\n logger.info(f\"Building SNOMED lookup for {len(unique_drugs)} unique drugs...\")\n\n # Build drug -> list of DrugSnomedMapping dict\n drug_snomed_map: dict[str, list[DrugSnomedMapping]] = {}\n all_snomed_codes: set[str] = set()\n snomed_to_drug_searchterm: dict[str, list[tuple[str, str, str]]] = {} # snomed -> [(drug, search_term, primary_dir), ...]\n\n for drug_name in unique_drugs:\n mappings = get_drug_snomed_codes(drug_name, db_manager)\n drug_snomed_map[drug_name] = mappings\n\n for m in mappings:\n all_snomed_codes.add(m.snomed_code)\n if m.snomed_code not in snomed_to_drug_searchterm:\n snomed_to_drug_searchterm[m.snomed_code] = []\n snomed_to_drug_searchterm[m.snomed_code].append(\n (drug_name, m.search_term, m.primary_directorate)\n )\n\n logger.info(f\"Total SNOMED codes to check: {len(all_snomed_codes)}\")\n\n # Step 3: Check Snowflake availability\n if not SNOWFLAKE_AVAILABLE or not is_snowflake_configured():\n logger.warning(\"Snowflake not available - returning fallback for all patients\")\n result_df = unique_pairs[['UPID', 'Directory']].copy()\n result_df['Indication_Group'] = result_df['Directory'] + \" (no GP dx)\"\n result_df['Source'] = \"FALLBACK\"\n return result_df[['UPID', 'Indication_Group', 'Source']].drop_duplicates(subset=['UPID'])\n\n if connector is None:\n connector = get_connector()\n\n # Step 4: Query GP records for all patients in batches\n # The query finds the most recent matching SNOMED code for each patient\n\n # Get unique PseudoNHSNoLinked values (each = one patient in GP records)\n unique_patients = unique_pairs[['PseudoNHSNoLinked', 'UPID', 'Directory']].drop_duplicates(subset=['PseudoNHSNoLinked'])\n patient_pseudonyms = unique_patients['PseudoNHSNoLinked'].tolist()\n\n logger.info(f\"Querying GP records for {len(patient_pseudonyms)} unique patients in batches of {batch_size}...\")\n\n # Results dict: PersonKey -> (snomed_code, event_date)\n gp_matches: dict[str, tuple[str, Any]] = {}\n\n # Convert SNOMED codes to list for query\n snomed_list = list(all_snomed_codes)\n\n if not snomed_list:\n logger.warning(\"No SNOMED codes to check - returning fallback for all patients\")\n result_df = unique_pairs[['UPID', 'Directory']].copy()\n result_df['Indication_Group'] = result_df['Directory'] + \" (no GP dx)\"\n result_df['Source'] = \"FALLBACK\"\n return result_df[['UPID', 'Indication_Group', 'Source']].drop_duplicates(subset=['UPID'])\n\n # Build SNOMED IN clause (reused across batches)\n snomed_placeholders = \", \".join([\"%s\"] * len(snomed_list))\n\n # Process patients in batches\n for batch_start in range(0, len(patient_pseudonyms), batch_size):\n batch_end = min(batch_start + batch_size, len(patient_pseudonyms))\n batch_pseudonyms = patient_pseudonyms[batch_start:batch_end]\n\n logger.info(f\"Batch {batch_start//batch_size + 1}: patients {batch_start} to {batch_end}\")\n\n # Build patient IN clause\n patient_placeholders = \", \".join([\"%s\"] * len(batch_pseudonyms))\n\n # Query to find all matching SNOMED codes for these patients\n # We'll get all matches and pick the most recent per patient in Python\n query = f'''\n SELECT\n \"PatientPseudonym\",\n \"SNOMEDCode\",\n \"EventDateTime\"\n FROM DATA_HUB.PHM.\"PrimaryCareClinicalCoding\"\n WHERE \"PatientPseudonym\" IN ({patient_placeholders})\n AND \"SNOMEDCode\" IN ({snomed_placeholders})\n ORDER BY \"PatientPseudonym\", \"EventDateTime\" DESC\n '''\n\n params = tuple(batch_pseudonyms) + tuple(snomed_list)\n\n try:\n results = connector.execute_dict(query, params)\n\n # Process results - pick most recent per patient\n for row in results:\n person_key = row.get(\"PatientPseudonym\")\n snomed_code = row.get(\"SNOMEDCode\")\n event_date = row.get(\"EventDateTime\")\n\n if person_key and snomed_code:\n # Keep only if we haven't seen this patient yet (first = most recent due to ORDER BY)\n if person_key not in gp_matches:\n gp_matches[person_key] = (snomed_code, event_date)\n\n except Exception as e:\n logger.error(f\"Error querying GP records for batch: {e}\")\n # Continue with other batches\n\n logger.info(f\"Found GP matches for {len(gp_matches)} patients\")\n\n # Step 5: Build result DataFrame\n # For each unique_pair, determine Indication_Group based on match status\n results_list = []\n\n # We need to dedupe by UPID - a patient might be on multiple drugs\n # Strategy: For each UPID, use the most recent match (if any)\n upid_to_match: dict[str, tuple[str, str]] = {} # UPID -> (Indication_Group, Source)\n\n for _, row in unique_pairs.iterrows():\n upid = row['UPID']\n drug_name = row['Drug Name']\n patient_pseudonym = row['PseudoNHSNoLinked']\n directory = row['Directory']\n\n # Check if patient has GP match (using PseudoNHSNoLinked which matches PatientPseudonym in GP)\n if patient_pseudonym in gp_matches:\n matched_snomed, event_date = gp_matches[patient_pseudonym]\n\n # Find the search_term for this SNOMED code and drug\n # (A SNOMED code might map to multiple drugs with different search_terms)\n if matched_snomed in snomed_to_drug_searchterm:\n # Look for match with current drug first\n search_term = None\n for drug, st, pd in snomed_to_drug_searchterm[matched_snomed]:\n if drug.upper() == drug_name.upper():\n search_term = st\n break\n # If no drug-specific match, use any match\n if search_term is None:\n search_term = snomed_to_drug_searchterm[matched_snomed][0][1]\n\n # Only update if we don't have a match for this UPID yet\n if upid not in upid_to_match:\n upid_to_match[upid] = (search_term, \"DIAGNOSIS\")\n else:\n # Shouldn't happen but fallback just in case\n if upid not in upid_to_match:\n upid_to_match[upid] = (directory + \" (no GP dx)\", \"FALLBACK\")\n else:\n # No GP match - use fallback\n if upid not in upid_to_match:\n upid_to_match[upid] = (directory + \" (no GP dx)\", \"FALLBACK\")\n\n # Build result DataFrame\n for upid, (indication_group, source) in upid_to_match.items():\n results_list.append({\n 'UPID': upid,\n 'Indication_Group': indication_group,\n 'Source': source,\n })\n\n result_df = pd.DataFrame(results_list)\n\n # Log statistics\n diagnosis_count = len([s for s in result_df['Source'] if s == \"DIAGNOSIS\"])\n fallback_count = len([s for s in result_df['Source'] if s == \"FALLBACK\"])\n total = len(result_df)\n\n logger.info(f\"Indication lookup complete:\")\n logger.info(f\" Total unique patients: {total}\")\n logger.info(f\" DIAGNOSIS matches: {diagnosis_count} ({100*diagnosis_count/total:.1f}%)\")\n logger.info(f\" FALLBACK (no GP match): {fallback_count} ({100*fallback_count/total:.1f}%)\")\n\n return result_df\n\n\n# === Drug-to-indication mapping from DimSearchTerm.csv ===\n\n\n# Merge related Search_Terms into canonical names.\n# Asthma variants are clinically the same condition at different severity levels.\n# Urticaria is a separate condition  do NOT merge with asthma.\nSEARCH_TERM_MERGE_MAP: dict[str, str] = {\n \"allergic asthma\": \"asthma\",\n \"severe persistent allergic asthma\": \"asthma\",\n}\n\n\ndef load_drug_indication_mapping(\n csv_path: Optional[str] = None,\n) -> tuple[dict[str, list[str]], dict[str, list[str]]]:\n \"\"\"\n Load the drug-to-Search_Term mapping from DimSearchTerm.csv.\n\n Builds two lookup dicts:\n - fragment_to_search_terms: drug fragment (UPPERCASE) -> list of Search_Terms containing it\n - search_term_to_fragments: search_term -> list of drug fragments (UPPERCASE)\n\n DimSearchTerm.csv has columns: Search_Term, CleanedDrugName, PrimaryDirectorate\n CleanedDrugName is pipe-separated (e.g., \"ADALIMUMAB|GOLIMUMAB|IXEKIZUMAB\").\n\n Note: A Search_Term can appear multiple times with different PrimaryDirectorates\n (e.g., \"diabetes\" appears under both DIABETIC MEDICINE and OPHTHALMOLOGY).\n Drug fragments from all rows for the same Search_Term are combined.\n\n Asthma-related Search_Terms (\"allergic asthma\", \"severe persistent allergic asthma\")\n are merged into \"asthma\" to match the CLUSTER_MAPPING_SQL normalization.\n \"urticaria\" stays separate.\n\n Args:\n csv_path: Path to DimSearchTerm.csv. Defaults to data/DimSearchTerm.csv.\n\n Returns:\n Tuple of (fragment_to_search_terms, search_term_to_fragments)\n \"\"\"\n if csv_path is None:\n csv_path = str(Path(__file__).parent.parent / \"data\" / \"DimSearchTerm.csv\")\n\n fragment_to_search_terms: dict[str, list[str]] = {}\n search_term_to_fragments: dict[str, list[str]] = {}\n\n try:\n with open(csv_path, \"r\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n for row in reader:\n search_term = row.get(\"Search_Term\", \"\").strip()\n drug_names_raw = row.get(\"CleanedDrugName\", \"\").strip()\n\n # Normalize asthma variants to canonical \"asthma\"\n search_term = SEARCH_TERM_MERGE_MAP.get(search_term, search_term)\n\n if not search_term or not drug_names_raw:\n continue\n\n fragments = [frag.strip().upper() for frag in drug_names_raw.split(\"|\") if frag.strip()]\n\n # Build search_term -> fragments (accumulate for duplicate Search_Terms)\n if search_term not in search_term_to_fragments:\n search_term_to_fragments[search_term] = []\n for frag in fragments:\n if frag not in search_term_to_fragments[search_term]:\n search_term_to_fragments[search_term].append(frag)\n\n # Build fragment -> search_terms\n for frag in fragments:\n if frag not in fragment_to_search_terms:\n fragment_to_search_terms[frag] = []\n if search_term not in fragment_to_search_terms[frag]:\n fragment_to_search_terms[frag].append(search_term)\n\n logger.info(\n f\"Loaded drug-indication mapping: {len(search_term_to_fragments)} Search_Terms, \"\n f\"{len(fragment_to_search_terms)} drug fragments\"\n )\n\n except FileNotFoundError:\n logger.error(f\"DimSearchTerm.csv not found at {csv_path}\")\n except Exception as e:\n logger.error(f\"Error loading DimSearchTerm.csv: {e}\")\n\n return fragment_to_search_terms, search_term_to_fragments\n\n\ndef get_search_terms_for_drug(\n drug_name: str,\n search_term_to_fragments: dict[str, list[str]],\n) -> list[str]:\n \"\"\"\n Get all Search_Terms that list a given drug using substring matching.\n\n Checks if any drug fragment from DimSearchTerm is a SUBSTRING of the given\n drug name (case-insensitive). This handles both exact matches (ADALIMUMAB)\n and partial fragments (PEGYLATED, INHALED).\n\n Args:\n drug_name: HCD drug name (e.g., \"ADALIMUMAB 40MG\", \"PEGYLATED LIPOSOMAL DOXORUBICIN\")\n search_term_to_fragments: Mapping of search_term -> list of drug fragments\n\n Returns:\n List of Search_Terms whose drug fragments match the drug name\n \"\"\"\n drug_name_upper = drug_name.upper()\n matched_terms: list[str] = []\n\n for search_term, fragments in search_term_to_fragments.items():\n for frag in fragments:\n if frag in drug_name_upper:\n matched_terms.append(search_term)\n break # One matching fragment is enough for this Search_Term\n\n return matched_terms\n\n\ndef assign_drug_indications(\n df: \"pd.DataFrame\",\n gp_matches_df: \"pd.DataFrame\",\n search_term_to_fragments: dict[str, list[str]],\n) -> \"tuple[pd.DataFrame, pd.DataFrame]\":\n \"\"\"\n Assign drug-aware indications by cross-referencing GP diagnoses with drug mappings.\n\n For each UPID + Drug Name pair in the HCD data:\n 1. Look up patient's GP-matched Search_Terms (via PseudoNHSNoLinked  gp_matches_df)\n 2. Look up which Search_Terms list this drug (via search_term_to_fragments)\n 3. Intersect = valid indications for this drug-patient pair\n 4. If 1 match: use it\n 5. If multiple: pick highest code_frequency (most GP coding = most likely indication)\n 6. If tied frequency: alphabetical Search_Term for determinism\n 7. If 0 matches: fallback to \"{Directory} (no GP dx)\"\n\n Modifies UPID to include indication: \"{UPID}|{search_term}\" or \"{UPID}|{Directory} (no GP dx)\".\n This makes drugs under different indications appear as separate pathways.\n\n Args:\n df: HCD DataFrame with columns: UPID, Drug Name, PseudoNHSNoLinked, Directory\n gp_matches_df: GP matches from get_patient_indication_groups() with columns:\n PatientPseudonym, Search_Term, code_frequency\n (multiple rows per patient, one per matched Search_Term)\n search_term_to_fragments: From load_drug_indication_mapping()[1].\n Maps search_term -> list of drug fragments (UPPERCASE).\n\n Returns:\n Tuple of (modified_df, indication_df):\n - modified_df: Copy of df with UPID replaced by \"{UPID}|{indication}\"\n - indication_df: DataFrame indexed by modified UPID with 'Directory' column\n containing the Search_Term (or fallback label) for pathway hierarchy\n \"\"\"\n import pandas as pd\n\n modified_df = df.copy()\n\n # Build GP match lookup: PseudoNHSNoLinked -> {Search_Term: code_frequency}\n gp_lookup: dict[str, dict[str, int]] = {}\n if not gp_matches_df.empty:\n for _, row in gp_matches_df.iterrows():\n pseudo = row['PatientPseudonym']\n term = row['Search_Term']\n freq = int(row.get('code_frequency', 0))\n if pseudo not in gp_lookup:\n gp_lookup[pseudo] = {}\n gp_lookup[pseudo][term] = freq\n\n logger.info(f\"GP lookup built: {len(gp_lookup)} patients with GP matches\")\n\n # Cache drug -> Search_Terms lookups to avoid recomputing per row\n drug_search_terms_cache: dict[str, list[str]] = {}\n\n def get_drug_terms(drug_name: str) -> list[str]:\n if drug_name not in drug_search_terms_cache:\n drug_search_terms_cache[drug_name] = get_search_terms_for_drug(\n drug_name, search_term_to_fragments\n )\n return drug_search_terms_cache[drug_name]\n\n # Process each row: determine indication for each UPID + Drug Name\n # We work at the (UPID, Drug Name) pair level, then apply to all rows\n # Key: (UPID, Drug Name) -> (matched_search_term_or_fallback, is_diagnosis)\n pair_indication_cache: dict[tuple[str, str], tuple[str, bool]] = {}\n\n # Get unique (UPID, Drug Name, PseudoNHSNoLinked, Directory) combos\n required_cols = ['UPID', 'Drug Name', 'PseudoNHSNoLinked', 'Directory']\n unique_pairs = modified_df[required_cols].drop_duplicates(\n subset=['UPID', 'Drug Name']\n )\n\n match_count = 0\n fallback_count = 0\n tiebreak_count = 0\n\n for _, pair_row in unique_pairs.iterrows():\n upid = pair_row['UPID']\n drug_name = pair_row['Drug Name']\n pseudo = pair_row['PseudoNHSNoLinked']\n directory = pair_row['Directory']\n\n # Get Search_Terms this drug maps to\n drug_terms = get_drug_terms(drug_name)\n\n # Get patient's GP-matched Search_Terms\n patient_gp_terms = gp_lookup.get(pseudo, {}) if pd.notna(pseudo) else {}\n\n # Intersect: Search_Terms that list this drug AND patient has GP dx for\n valid_indications = {\n term: patient_gp_terms[term]\n for term in drug_terms\n if term in patient_gp_terms\n }\n\n if len(valid_indications) == 1:\n matched_term = next(iter(valid_indications))\n pair_indication_cache[(upid, drug_name)] = (matched_term, True)\n match_count += 1\n\n elif len(valid_indications) > 1:\n # Tiebreaker: highest code_frequency, then alphabetical\n sorted_terms = sorted(\n valid_indications.items(),\n key=lambda x: (-x[1], x[0]),\n )\n matched_term = sorted_terms[0][0]\n pair_indication_cache[(upid, drug_name)] = (matched_term, True)\n match_count += 1\n tiebreak_count += 1\n\n else:\n # No intersection: fallback to directory\n if pd.notna(directory):\n fallback_label = f\"{directory} (no GP dx)\"\n else:\n fallback_label = \"UNKNOWN (no GP dx)\"\n pair_indication_cache[(upid, drug_name)] = (fallback_label, False)\n fallback_count += 1\n\n total_pairs = len(unique_pairs)\n logger.info(f\"Drug-indication matching complete:\")\n logger.info(f\" Total UPID-Drug pairs: {total_pairs}\")\n logger.info(f\" Matched (GP dx + drug mapping): {match_count} ({100*match_count/total_pairs:.1f}%)\" if total_pairs > 0 else f\" Matched: 0\")\n logger.info(f\" Tiebreaker used: {tiebreak_count}\")\n logger.info(f\" Fallback (no match): {fallback_count} ({100*fallback_count/total_pairs:.1f}%)\" if total_pairs > 0 else f\" Fallback: 0\")\n\n # Apply modified UPIDs to all rows\n # Build vectorized lookup: original UPID + Drug Name -> modified UPID\n def build_modified_upid(row: \"pd.Series\") -> str:\n upid = row['UPID']\n drug_name = row['Drug Name']\n key = (upid, drug_name)\n if key in pair_indication_cache:\n indication, _ = pair_indication_cache[key]\n return f\"{upid}|{indication}\"\n # Shouldn't happen, but fallback\n return f\"{upid}|UNKNOWN (no GP dx)\"\n\n modified_df['UPID'] = modified_df.apply(build_modified_upid, axis=1)\n\n # Build indication_df: modified UPID -> Search_Term/fallback label\n # This maps each unique modified UPID to its indication for the pathway hierarchy\n indication_records: list[dict[str, str]] = []\n seen_upids: set[str] = set()\n\n for (original_upid, drug_name), (indication, is_diagnosis) in pair_indication_cache.items():\n modified_upid = f\"{original_upid}|{indication}\"\n if modified_upid not in seen_upids:\n indication_records.append({\n 'UPID': modified_upid,\n 'Directory': indication,\n })\n seen_upids.add(modified_upid)\n\n indication_df = pd.DataFrame(indication_records)\n if not indication_df.empty:\n indication_df = indication_df.set_index('UPID')\n\n logger.info(f\" Unique modified UPIDs: {len(indication_df)}\")\n\n # Log top indications\n if not indication_df.empty:\n top_terms = indication_df['Directory'].value_counts().head(5)\n logger.info(f\" Top 5 indications: {dict(top_terms)}\")\n\n return modified_df, indication_df\n\n\n# === NEW APPROACH: Query Snowflake directly using cluster CTE ===\n\n# The cluster query mapping (embedded from snomed_indication_mapping_query.sql)\n# This maps Search_Term -> Cluster_ID for ~148 clinical conditions\nCLUSTER_MAPPING_SQL = \"\"\"\nWITH SearchTermClusters AS (\n SELECT Search_Term, Cluster_ID FROM (VALUES\n ('acute lymphoblastic leukaemia', 'HAEMCANMORPH_COD'),\n ('acute myeloid leukaemia', 'C19HAEMCAN_COD'),\n ('acute promyelocytic leukaemia', 'HAEMCANMORPH_COD'),\n ('asthma', 'AST_COD'),\n ('allergic rhinitis', 'MILDINTAST_COD'),\n ('alzheimer''s disease', 'DEMALZ_COD'),\n ('amyloidosis', 'AMYLOID_COD'),\n ('anaemia', 'eFI2_AnaemiaTimeSensitive'),\n ('anaplastic large cell lymphoma', 'C19HAEMCAN_COD'),\n ('apixaban', 'DOACCON_COD'),\n ('aplastic anaemia', 'eFI2_AnaemiaEver'),\n ('arthritis', 'eFI2_InflammatoryArthritis'),\n ('asthma', 'eFI2_Asthma'),\n ('atopic dermatitis', 'ATOPDERM_COD'),\n ('atrial fibrillation', 'eFI2_AtrialFibrillation'),\n ('attention deficit hyperactivity disorder', 'ADHD_COD'),\n ('bipolar disorder', 'MH_COD'),\n ('bladder', 'eFI2_UrinaryIncontinence'),\n ('breast cancer', 'BRCANSCR_COD'),\n ('cardiomyopathy', 'eFI2_HarmfulDrinking'),\n ('cardiovascular disease', 'CVDRISKASS_COD'),\n ('cervical cancer', 'CSDEC_COD'),\n ('cholangiocarcinoma', 'eFI2_Cancer'),\n ('chronic kidney disease', 'CKD_COD'),\n ('chronic liver disease', 'eFI2_LiverProblems'),\n ('chronic lymphocytic leukaemia', 'EPPHAEMCAN_COD'),\n ('chronic myeloid leukaemia', 'EPPHAEMCAN_COD'),\n ('chronic obstructive pulmonary disease', 'eFI2_COPD'),\n ('colon cancer', 'eFI2_Cancer'),\n ('colorectal cancer', 'GICANREF_COD'),\n ('constipation', 'CHRONCONSTIP_COD'),\n ('covid-19', 'POSSPOSTCOVID_COD'),\n ('crohn''s disease', 'eFI2_InflammatoryBowelDisease'),\n ('cutaneous t-cell lymphoma', 'C19HAEMCAN_COD'),\n ('cystic fibrosis', 'CUST_ICB_CYSTIC_FIBROSIS'),\n ('deep vein thrombosis', 'VTE_COD'),\n ('depression', 'eFI2_Depression'),\n ('diabetes', 'eFI2_DiabetesEver'),\n ('diabetic retinopathy', 'DRSELIGIBILITY_COD'),\n ('diffuse large b-cell lymphoma', 'C19HAEMCAN_COD'),\n ('dravet syndrome', 'EPIL_COD'),\n ('drug misuse', 'ILLSUBINT_COD'),\n ('dyspepsia', 'eFI2_AbdominalPain'),\n ('epilepsy', 'eFI2_Seizures'),\n ('fallopian tube', 'STERIL_COD'),\n ('follicular lymphoma', 'C19HAEMCAN_COD'),\n ('gastric cancer', 'eFI2_Cancer'),\n ('giant cell arteritis', 'GCA_COD'),\n ('glioma', 'NHAEMCANMORPH_COD'),\n ('gout', 'eFI2_InflammatoryArthritis'),\n ('graft versus host disease', 'GVHD_COD'),\n ('granulomatosis with polyangiitis', 'WEGENERVASC_COD'),\n ('growth hormone deficiency', 'HYPOPITUITARY_COD'),\n ('hand eczema', 'ECZEMA_COD'),\n ('heart failure', 'eFI2_HeartFailure'),\n ('hepatitis b', 'HEPBCVAC_COD'),\n ('hepatocellular carcinoma', 'eFI2_Cancer'),\n ('hiv', 'PREFLANG_COD'),\n ('hodgkin lymphoma', 'HAEMCANMORPH_COD'),\n ('hormone receptor', 'eFI2_ThyroidProblems'),\n ('hypercholesterolaemia', 'CLASSFH_COD'),\n ('immune thrombocytopenia', 'ITP_COD'),\n ('influenza', 'FLUINVITE_COD'),\n ('insomnia', 'eFI2_SleepProblems'),\n ('irritable bowel syndrome', 'IBS_COD'),\n ('ischaemic stroke', 'OSTR_COD'),\n ('juvenile idiopathic arthritis', 'RARTHAD_COD'),\n ('kidney transplant', 'RENALTRANSP_COD'),\n ('leukaemia', 'eFI2_Cancer'),\n ('lung cancer', 'FTCANREF_COD'),\n ('lymphoma', 'C19HAEMCAN_COD'),\n ('macular degeneration', 'CUST_ICB_VISUAL_IMPAIRMENT'),\n ('macular oedema', 'CUST_ICB_VISUAL_IMPAIRMENT'),\n ('major depressive episodes', 'eFI2_Depression'),\n ('malignant melanoma', 'eFI2_Cancer'),\n ('malignant pleural mesothelioma', 'LUNGCAN_COD'),\n ('manic episode', 'MH_COD'),\n ('mantle cell lymphoma', 'HAEMCANMORPH_COD'),\n ('melanoma', 'eFI2_Cancer'),\n ('merkel cell carcinoma', 'C19CAN_COD'),\n ('migraine', 'eFI2_Headache'),\n ('motor neurone disease', 'MND_COD'),\n ('multiple myeloma', 'C19HAEMCAN_COD'),\n ('multiple sclerosis', 'MS_COD'),\n ('myelodysplastic', 'eFI2_AnaemiaEver'),\n ('myelofibrosis', 'MDS_COD'),\n ('myocardial infarction', 'eFI2_IschaemicHeartDisease'),\n ('myotonia', 'CNDATRISK2_COD'),\n ('narcolepsy', 'LD_COD'),\n ('neuroendocrine tumour', 'LUNGCAN_COD'),\n ('non-small cell lung cancer', 'LUNGCAN_COD'),\n ('non-small-cell lung cancer', 'FTCANREF_COD'),\n ('obesity', 'BMI30_COD'),\n ('osteoarthritis', 'CUST_ICB_OSTEOARTHRITIS'),\n ('osteoporosis', 'eFI2_Osteoporosis'),\n ('osteosarcoma', 'NHAEMCANMORPH_COD'),\n ('ovarian cancer', 'C19CAN_COD'),\n ('peripheral arterial disease', 'PADEXC_COD'),\n ('plaque psoriasis', 'PSORIASIS_COD'),\n ('polycystic kidney disease', 'EPPCONGMALF_COD'),\n ('polycythaemia vera', 'C19HAEMCAN_COD'),\n ('pregnancy', 'C19PREG_COD'),\n ('primary biliary cholangitis', 'eFI2_LiverProblems'),\n ('primary hypercholesterolaemia', 'FNFHYP_COD'),\n ('prostate cancer', 'EPPSOLIDCAN_COD'),\n ('psoriasis', 'PSORIASIS_COD'),\n ('psoriatic arthritis', 'RARTHAD_COD'),\n ('pulmonary embolism', 'eFI2_RespiratoryDiseaseTimeSensitive'),\n ('pulmonary fibrosis', 'ILD_COD'),\n ('relapsing multiple sclerosis', 'MS_COD'),\n ('renal cell carcinoma', 'C19CAN_COD'),\n ('renal transplantation', 'RENALTRANSP_COD'),\n ('retinal vein occlusion', 'CUST_ICB_VISUAL_IMPAIRMENT'),\n ('rheumatoid arthritis', 'eFI2_InflammatoryArthritis'),\n ('rivaroxaban', 'DOACCON_COD'),\n ('schizophrenia', 'MH_COD'),\n ('seizures', 'LSZFREQ_COD'),\n ('sepsis', 'C19ACTIVITY_COD'),\n ('asthma', 'SEVAST_COD'),\n ('sickle cell disease', 'SICKLE_COD'),\n ('sleep apnoea', 'CUST_ICB_NON_SEVERE_LDA'),\n ('smoking cessation', 'SMOKINGINT_COD'),\n ('soft tissue sarcoma', 'NHAEMCANMORPH_COD'),\n ('spinal muscular atrophy', 'MND_COD'),\n ('squamous cell', 'C19CAN_COD'),\n ('squamous cell carcinoma', 'C19CAN_COD'),\n ('stem cell transplant', 'ALLOTRANSP_COD'),\n ('stroke', 'eFI2_Stroke'),\n ('systemic lupus erythematosus', 'SLUPUS_COD'),\n ('systemic mastocytosis', 'HAEMCANMORPH_COD'),\n ('thrombocytopenic purpura', 'TTP_COD'),\n ('thrombotic thrombocytopenic purpura', 'TTP_COD'),\n ('thyroid cancer', 'C19CAN_COD'),\n ('tophaceous gout', 'CUST_ICB_OSTEOARTHRITIS'),\n ('transitional cell carcinoma', 'C19CAN_COD'),\n ('type 1 diabetes', 'DMTYPE1_COD'),\n ('type 2 diabetes', 'DMTYPE2_COD'),\n ('ulcerative colitis', 'eFI2_InflammatoryBowelDisease'),\n ('urothelial carcinoma', 'NHAEMCANMORPH_COD'),\n ('urticaria', 'XSAL_COD'),\n ('uveitis', 'CUST_ICB_VISUAL_IMPAIRMENT'),\n ('vascular disease', 'CVDINVITE_COD'),\n ('vasculitis', 'CRYOGLOBVASC_COD')\n ) AS t(Search_Term, Cluster_ID)\n),\n\nClusterCodes AS (\n SELECT\n stc.Search_Term,\n c.\"SNOMEDCode\",\n c.\"SNOMEDDescription\"\n FROM SearchTermClusters stc\n JOIN DATA_HUB.PHM.\"ClinicalCodingClusterSnomedCodes\" c\n ON stc.Cluster_ID = c.\"Cluster_ID\"\n WHERE c.\"SNOMEDCode\" IS NOT NULL\n),\n\nExplicitCodes AS (\n SELECT Search_Term, SNOMEDCode, SNOMEDDescription FROM (VALUES\n ('acute coronary syndrome', '837091000000100', 'Manual mapping'),\n ('ankylosing spondylitis', '162930007', 'Manual mapping'),\n ('ankylosing spondylitis', '239805001', 'Manual mapping'),\n ('ankylosing spondylitis', '239810002', 'Manual mapping'),\n ('ankylosing spondylitis', '239811003', 'Manual mapping'),\n ('ankylosing spondylitis', '394990003', 'Manual mapping'),\n ('ankylosing spondylitis', '429712009', 'Manual mapping'),\n ('ankylosing spondylitis', '441562009', 'Manual mapping'),\n ('ankylosing spondylitis', '441680005', 'Manual mapping'),\n ('ankylosing spondylitis', '441930001', 'Manual mapping'),\n ('axial spondyloarthritis', '723116002', 'Manual mapping'),\n ('choroidal neovascularisation', '380621000000102', 'Manual mapping'),\n ('choroidal neovascularisation', '733124000', 'Manual mapping')\n ) AS t(Search_Term, SNOMEDCode, SNOMEDDescription)\n),\n\nAllIndicationCodes AS (\n SELECT Search_Term, \"SNOMEDCode\" AS SNOMEDCode, \"SNOMEDDescription\" AS SNOMEDDescription\n FROM ClusterCodes\n UNION ALL\n SELECT Search_Term, SNOMEDCode, SNOMEDDescription\n FROM ExplicitCodes\n)\n\"\"\"\n\n\ndef get_patient_indication_groups(\n patient_pseudonyms: list[str],\n connector: Optional[SnowflakeConnector] = None,\n batch_size: int = 500,\n earliest_hcd_date: Optional[str] = None,\n) -> \"pd.DataFrame\":\n \"\"\"\n Batch lookup GP diagnosis-based indication groups using Snowflake cluster query.\n\n Returns ALL matching Search_Terms per patient with code_frequency (count of\n matching SNOMED codes). This enables drug-aware indication matching where\n each drug is cross-referenced against the patient's GP diagnoses.\n\n The query:\n 1. Uses the cluster mapping CTE to get all Search_Term -> SNOMED code mappings\n 2. Joins with PrimaryCareClinicalCoding to find patients with matching codes\n 3. Groups by patient + Search_Term and counts matching codes (code_frequency)\n 4. Optionally restricts to GP codes from earliest_hcd_date onwards\n\n Args:\n patient_pseudonyms: List of PseudoNHSNoLinked values (matches PatientPseudonym in GP records)\n connector: Optional SnowflakeConnector (defaults to singleton)\n batch_size: Number of patients per Snowflake query batch (default 500)\n earliest_hcd_date: Optional ISO date string (YYYY-MM-DD). If provided, only\n counts GP codes from this date onwards. Should be MIN(Intervention Date)\n from the HCD DataFrame to restrict to the HCD data window.\n\n Returns:\n DataFrame with columns:\n - PatientPseudonym: The patient identifier (PseudoNHSNoLinked value)\n - Search_Term: The matched indication (e.g., \"rheumatoid arthritis\")\n - code_frequency: Count of matching SNOMED codes for this Search_Term\n\n Multiple rows per patient (one per matched Search_Term).\n Patients not found in results have no matching GP diagnosis.\n \"\"\"\n import pandas as pd\n\n logger.info(f\"Starting Snowflake-direct indication lookup for {len(patient_pseudonyms)} patients...\")\n if earliest_hcd_date:\n logger.info(f\" Restricting GP codes to >= {earliest_hcd_date}\")\n\n # Handle edge case: empty patient list\n if not patient_pseudonyms:\n logger.warning(\"Empty patient list provided\")\n return pd.DataFrame(columns=['PatientPseudonym', 'Search_Term', 'code_frequency'])\n\n # Check Snowflake availability\n if not SNOWFLAKE_AVAILABLE:\n logger.error(\"Snowflake connector not available - cannot lookup GP records\")\n return pd.DataFrame(columns=['PatientPseudonym', 'Search_Term', 'code_frequency'])\n\n if not is_snowflake_configured():\n logger.error(\"Snowflake not configured - cannot lookup GP records\")\n return pd.DataFrame(columns=['PatientPseudonym', 'Search_Term', 'code_frequency'])\n\n if connector is None:\n connector = get_connector()\n\n # Results list to collect all matches\n all_results: list[dict] = []\n\n # Process patients in batches\n total_patients = len(patient_pseudonyms)\n for batch_start in range(0, total_patients, batch_size):\n batch_end = min(batch_start + batch_size, total_patients)\n batch_pseudonyms = patient_pseudonyms[batch_start:batch_end]\n batch_num = batch_start // batch_size + 1\n total_batches = (total_patients + batch_size - 1) // batch_size\n\n logger.info(f\"Batch {batch_num}/{total_batches}: patients {batch_start + 1} to {batch_end}\")\n\n # Build patient IN clause placeholders\n patient_placeholders = \", \".join([\"%s\"] * len(batch_pseudonyms))\n\n # Build WHERE clause with optional date filter\n date_filter = \"\"\n if earliest_hcd_date:\n date_filter = f\"\\n AND pc.\\\"EventDateTime\\\" >= %s\"\n\n # Build the full query with cluster CTE\n # Returns ALL matching Search_Terms per patient with code_frequency\n # code_frequency = COUNT of matching SNOMED codes per Search_Term per patient\n query = f\"\"\"\n{CLUSTER_MAPPING_SQL}\nSELECT\n pc.\"PatientPseudonym\" AS \"PatientPseudonym\",\n aic.Search_Term AS \"Search_Term\",\n COUNT(*) AS \"code_frequency\"\nFROM DATA_HUB.PHM.\"PrimaryCareClinicalCoding\" pc\nINNER JOIN AllIndicationCodes aic\n ON pc.\"SNOMEDCode\" = aic.SNOMEDCode\nWHERE pc.\"PatientPseudonym\" IN ({patient_placeholders}){date_filter}\nGROUP BY pc.\"PatientPseudonym\", aic.Search_Term\n\"\"\"\n\n # Build params: patient pseudonyms + optional date\n params = list(batch_pseudonyms)\n if earliest_hcd_date:\n params.append(earliest_hcd_date)\n\n try:\n results = connector.execute_dict(query, tuple(params))\n\n for row in results:\n all_results.append({\n 'PatientPseudonym': row.get('PatientPseudonym'),\n 'Search_Term': row.get('Search_Term'),\n 'code_frequency': row.get('code_frequency', 0),\n })\n\n logger.debug(f\"Batch {batch_num}: found {len(results)} patient-indication matches\")\n\n except Exception as e:\n logger.error(f\"Error querying GP records for batch {batch_num}: {e}\")\n # Continue with other batches - partial results are better than none\n\n # Build result DataFrame\n result_df = pd.DataFrame(all_results)\n\n # Log summary statistics\n if len(result_df) > 0:\n unique_patients = result_df['PatientPseudonym'].nunique()\n total_rows = len(result_df)\n match_rate = 100 * unique_patients / total_patients\n unique_terms = result_df['Search_Term'].nunique()\n avg_indications = total_rows / unique_patients if unique_patients > 0 else 0\n logger.info(f\"Indication lookup complete:\")\n logger.info(f\" Total patients queried: {total_patients}\")\n logger.info(f\" Patients with GP match: {unique_patients} ({match_rate:.1f}%)\")\n logger.info(f\" Total patient-indication rows: {total_rows} (avg {avg_indications:.1f} per patient)\")\n logger.info(f\" Unique Search_Terms found: {unique_terms}\")\n\n # Log top Search_Terms\n top_terms = result_df['Search_Term'].value_counts().head(5)\n logger.info(f\" Top 5 indications: {dict(top_terms)}\")\n else:\n logger.info(f\"Indication lookup complete: 0 matches from {total_patients} patients\")\n\n return result_df\n\n\n# Export public API\n__all__ = [\n # Dataclasses\n \"ClusterSnomedCodes\",\n \"IndicationValidationResult\",\n \"DrugIndicationMatchRate\",\n \"DrugSnomedMapping\",\n \"DirectSnomedMatchResult\",\n \"DirectorateAssignment\",\n # Cluster-based lookup functions (existing)\n \"get_drug_clusters\",\n \"get_drug_cluster_ids\",\n \"get_cluster_snomed_codes\",\n \"patient_has_indication\",\n \"validate_indication\",\n \"get_indication_match_rate\",\n \"batch_validate_indications\",\n \"get_available_clusters\",\n # Direct SNOMED lookup functions (new)\n \"get_drug_snomed_codes\",\n \"patient_has_indication_direct\",\n # Diagnosis-based directorate assignment\n \"get_directorate_from_diagnosis\",\n # Batch lookup for indication groups\n \"batch_lookup_indication_groups\",\n # Drug-indication mapping from DimSearchTerm.csv\n \"SEARCH_TERM_MERGE_MAP\",\n \"load_drug_indication_mapping\",\n \"get_search_terms_for_drug\",\n # Snowflake-direct indication lookup (new approach)\n \"get_patient_indication_groups\",\n \"CLUSTER_MAPPING_SQL\",\n]\n","structuredPatch":[{"oldStart":1736,"oldLines":6,"newStart":1736,"newLines":8,"lines":[" \"SEARCH_TERM_MERGE_MAP\","," \"load_drug_indication_mapping\","," \"get_search_terms_for_drug\",","+ # Drug-aware indication assignment","+ \"assign_drug_indications\","," # Snowflake-direct indication lookup (new approach)"," \"get_patient_indication_groups\","," \"CLUSTER_MAPPING_SQL\","]}],"userModified":false,"replaceAll":false}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01NoAiBAvc87vnLf4cK5sRRR","type":"message","role":"assistant","content":[{"type":"text","text":"Now let me validate the code. Running py_compile and import checks."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":331,"cache_read_input_tokens":122476,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":331},"output_tokens":3,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"1a766b22-a455-4184-8799-076401f905be"}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01NoAiBAvc87vnLf4cK5sRRR","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01VGRE5FNmB4KU4uVApo3Fw8","name":"TodoWrite","input":{"todos":[{"content":"Read project files (progress.txt, IMPLEMENTATION_PLAN.md, guardrails.md)","status":"completed","activeForm":"Reading project files"},{"content":"Build assign_drug_indications() function (Task 2.1 + 2.2)","status":"completed","activeForm":"Building assign_drug_indications() function"},{"content":"Validate code (py_compile, import check, mock data test)","status":"in_progress","activeForm":"Validating code"},{"content":"Commit and update progress.txt","status":"pending","activeForm":"Committing and updating progress"}]}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":331,"cache_read_input_tokens":122476,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":331},"output_tokens":3,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"250e0d6a-df8d-4a12-a633-99431915b14d"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01VGRE5FNmB4KU4uVApo3Fw8","type":"tool_result","content":"Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable"}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"038a97a4-7513-4aee-8224-c15356c9f4f6","tool_use_result":{"oldTodos":[{"content":"Read project files (progress.txt, IMPLEMENTATION_PLAN.md, guardrails.md)","status":"completed","activeForm":"Reading project files"},{"content":"Build assign_drug_indications() function (Task 2.1 + 2.2)","status":"in_progress","activeForm":"Building assign_drug_indications() function"},{"content":"Validate code (py_compile, import check, mock data test)","status":"pending","activeForm":"Validating code"},{"content":"Commit and update progress.txt","status":"pending","activeForm":"Committing and updating progress"}],"newTodos":[{"content":"Read project files (progress.txt, IMPLEMENTATION_PLAN.md, guardrails.md)","status":"completed","activeForm":"Reading project files"},{"content":"Build assign_drug_indications() function (Task 2.1 + 2.2)","status":"completed","activeForm":"Building assign_drug_indications() function"},{"content":"Validate code (py_compile, import check, mock data test)","status":"in_progress","activeForm":"Validating code"},{"content":"Commit and update progress.txt","status":"pending","activeForm":"Committing and updating progress"}]}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01JUhtLepXTmi7sRQtuCQwPw","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_012bDUoKJyAKgfJ9Hwx4Lzbv","name":"Bash","input":{"command":"cd \"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\" && python -m py_compile data_processing/diagnosis_lookup.py","description":"Compile check diagnosis_lookup.py"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":269,"cache_read_input_tokens":122807,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":269},"output_tokens":26,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"dab072ac-82e3-41fa-8460-b742a0289145"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_012bDUoKJyAKgfJ9Hwx4Lzbv","type":"tool_result","content":"","is_error":false}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"47090336-99be-4ddc-aed3-1eff74614322","tool_use_result":{"stdout":"","stderr":"","interrupted":false,"isImage":false}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01PhwWmUUeXKRh33rupxgqyX","type":"message","role":"assistant","content":[{"type":"text","text":"Syntax check passed. Now import check."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":138,"cache_read_input_tokens":123076,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":138},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"6b427c6b-439f-495e-835e-c1b39505ecaa"}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01PhwWmUUeXKRh33rupxgqyX","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_013usYF9Rcw6FWBnRYg1NFWY","name":"Bash","input":{"command":"cd \"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\" && python -c \"from data_processing.diagnosis_lookup import assign_drug_indications, load_drug_indication_mapping, get_search_terms_for_drug; print('Import OK')\"","description":"Import check for new and existing functions"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":138,"cache_read_input_tokens":123076,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":138},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"9072947e-2c6e-464f-be79-206925117516"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_013usYF9Rcw6FWBnRYg1NFWY","type":"tool_result","content":"Import OK","is_error":false}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"4e2d21ff-ff52-4e57-90b6-72beb13da1a6","tool_use_result":{"stdout":"Import OK\r","stderr":"","interrupted":false,"isImage":false}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_019QtsYDMQqoCF4tmWQZ8h93","type":"message","role":"assistant","content":[{"type":"text","text":"Import check passed. Now let me test with mock data to verify the function works correctly ÔÇö this covers Task 2.2 (tiebreaker logic) as well."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":164,"cache_read_input_tokens":123214,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":164},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"0fbc5583-866f-4179-b7ff-31fa2dba022a"}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_019QtsYDMQqoCF4tmWQZ8h93","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_0134izEQP46fRzp1zbL5Vi1q","name":"Bash","input":{"command":"cd \"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\" && python -c \"\nimport pandas as pd\nfrom data_processing.diagnosis_lookup import assign_drug_indications, load_drug_indication_mapping, get_search_terms_for_drug\n\n# Load real drug mapping\nfrag_to_st, st_to_frags = load_drug_indication_mapping()\nprint(f'Loaded: {len(st_to_frags)} Search_Terms, {len(frag_to_st)} fragments')\n\n# Create mock HCD data\ndf = pd.DataFrame({\n 'UPID': ['RMV111', 'RMV111', 'RMV222', 'RMV333', 'RMV333'],\n 'Drug Name': ['ADALIMUMAB 40MG', 'OMALIZUMAB', 'ADALIMUMAB', 'TOCILIZUMAB', 'INFLIXIMAB'],\n 'PseudoNHSNoLinked': ['NHS111', 'NHS111', 'NHS222', 'NHS333', 'NHS333'],\n 'Directory': ['RHEUMATOLOGY', 'THORACIC MEDICINE', 'RHEUMATOLOGY', 'RHEUMATOLOGY', 'GASTRO'],\n})\n\n# Create mock GP matches (multiple rows per patient with code_frequency)\ngp_matches_df = pd.DataFrame({\n 'PatientPseudonym': ['NHS111', 'NHS111', 'NHS222', 'NHS222'],\n 'Search_Term': ['rheumatoid arthritis', 'asthma', 'rheumatoid arthritis', 'crohn\\\\'s disease'],\n 'code_frequency': [47, 12, 3, 2],\n})\n\nprint()\nprint('--- Test 1: Basic drug-indication matching ---')\nmodified_df, indication_df = assign_drug_indications(df, gp_matches_df, st_to_frags)\n\nprint()\nprint('Modified UPIDs:')\nfor _, row in modified_df.iterrows():\n print(f' {row[\\\"Drug Name\\\"]:25s} -> {row[\\\"UPID\\\"]}')\n\nprint()\nprint('Indication DataFrame:')\nprint(indication_df)\n\n# Verify expected results\nprint()\nprint('--- Verification ---')\n# Patient RMV111 on ADALIMUMAB + GP dx for RA + asthma: ADALIMUMAB should match RA\nada_upid = modified_df[modified_df['Drug Name'] == 'ADALIMUMAB 40MG']['UPID'].values[0]\nassert 'rheumatoid arthritis' in ada_upid, f'ADALIMUMAB should match RA, got: {ada_upid}'\nprint(f'OK: ADALIMUMAB matched to RA: {ada_upid}')\n\n# Patient RMV111 on OMALIZUMAB + GP dx for asthma: OMALIZUMAB should match asthma \noma_upid = modified_df[modified_df['Drug Name'] == 'OMALIZUMAB']['UPID'].values[0]\nassert 'asthma' in oma_upid, f'OMALIZUMAB should match asthma, got: {oma_upid}'\nprint(f'OK: OMALIZUMAB matched to asthma: {oma_upid}')\n\n# Patient RMV222 on ADALIMUMAB + GP dx for RA (47) + crohn's (2): tiebreaker picks RA\nada2_upid = modified_df[(modified_df['UPID'].str.startswith('RMV222')) & (modified_df['Drug Name'] == 'ADALIMUMAB')]['UPID'].values[0]\nassert 'rheumatoid arthritis' in ada2_upid, f'Tiebreaker should pick RA (code_freq 3 vs 2), got: {ada2_upid}'\nprint(f'OK: Tiebreaker picked RA over crohns for ADALIMUMAB: {ada2_upid}')\n\n# Patient RMV333 has no GP match -> fallback\ntoci_upid = modified_df[modified_df['Drug Name'] == 'TOCILIZUMAB']['UPID'].values[0]\nassert '(no GP dx)' in toci_upid, f'No GP match should fallback, got: {toci_upid}'\nprint(f'OK: No GP match falls back: {toci_upid}')\n\n# Same patient different indications = different modified UPIDs\nada1_upid = modified_df[modified_df['Drug Name'] == 'ADALIMUMAB 40MG']['UPID'].values[0]\noma1_upid = modified_df[modified_df['Drug Name'] == 'OMALIZUMAB']['UPID'].values[0]\nassert ada1_upid != oma1_upid, 'Different drugs with different indications should have different UPIDs'\nprint(f'OK: Different indications = different UPIDs')\n\nprint()\nprint('ALL TESTS PASSED')\n\"\n","description":"Test assign_drug_indications with mock data","timeout":30000}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":164,"cache_read_input_tokens":123214,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":164},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"f3709871-362c-4147-a29f-4a64040e3e6a"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_0134izEQP46fRzp1zbL5Vi1q","type":"tool_result","content":"Loaded: 162 Search_Terms, 346 fragments\r\n\r\n--- Test 1: Basic drug-indication matching ---\r\n\r\nModified UPIDs:\r\n ADALIMUMAB 40MG -> RMV111|rheumatoid arthritis\r\n OMALIZUMAB -> RMV111|asthma\r\n ADALIMUMAB -> RMV222|rheumatoid arthritis\r\n TOCILIZUMAB -> RMV333|RHEUMATOLOGY (no GP dx)\r\n INFLIXIMAB -> RMV333|GASTRO (no GP dx)\r\n\r\nIndication DataFrame:\r\n Directory\r\nUPID \r\nRMV111|rheumatoid arthritis rheumatoid arthritis\r\nRMV111|asthma asthma\r\nRMV222|rheumatoid arthritis rheumatoid arthritis\r\nRMV333|RHEUMATOLOGY (no GP dx) RHEUMATOLOGY (no GP dx)\r\nRMV333|GASTRO (no GP dx) GASTRO (no GP dx)\r\n\r\n--- Verification ---\r\nOK: ADALIMUMAB matched to RA: RMV111|rheumatoid arthritis\r\nOK: OMALIZUMAB matched to asthma: RMV111|asthma\r\nOK: Tiebreaker picked RA over crohns for ADALIMUMAB: RMV222|rheumatoid arthritis\r\nOK: No GP match falls back: RMV333|RHEUMATOLOGY (no GP dx)\r\nOK: Different indications = different UPIDs\r\n\r\nALL TESTS PASSED","is_error":false}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"af65d06e-caaa-472f-be7e-c36da21719a1","tool_use_result":{"stdout":"Loaded: 162 Search_Terms, 346 fragments\r\n\r\n--- Test 1: Basic drug-indication matching ---\r\n\r\nModified UPIDs:\r\n ADALIMUMAB 40MG -> RMV111|rheumatoid arthritis\r\n OMALIZUMAB -> RMV111|asthma\r\n ADALIMUMAB -> RMV222|rheumatoid arthritis\r\n TOCILIZUMAB -> RMV333|RHEUMATOLOGY (no GP dx)\r\n INFLIXIMAB -> RMV333|GASTRO (no GP dx)\r\n\r\nIndication DataFrame:\r\n Directory\r\nUPID \r\nRMV111|rheumatoid arthritis rheumatoid arthritis\r\nRMV111|asthma asthma\r\nRMV222|rheumatoid arthritis rheumatoid arthritis\r\nRMV333|RHEUMATOLOGY (no GP dx) RHEUMATOLOGY (no GP dx)\r\nRMV333|GASTRO (no GP dx) GASTRO (no GP dx)\r\n\r\n--- Verification ---\r\nOK: ADALIMUMAB matched to RA: RMV111|rheumatoid arthritis\r\nOK: OMALIZUMAB matched to asthma: RMV111|asthma\r\nOK: Tiebreaker picked RA over crohns for ADALIMUMAB: RMV222|rheumatoid arthritis\r\nOK: No GP match falls back: RMV333|RHEUMATOLOGY (no GP dx)\r\nOK: Different indications = different UPIDs\r\n\r\nALL TESTS PASSED\r","stderr":"","interrupted":false,"isImage":false}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01UPQoeu2Zjh44xNGY7QdpUS","type":"message","role":"assistant","content":[{"type":"text","text":"All tests pass. Let me also test the tiebreaker with equal frequencies to verify alphabetical fallback."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":1802,"cache_read_input_tokens":123378,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":1802},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"d4b1214f-4693-45d8-b07b-165d6acf44c6"}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01UPQoeu2Zjh44xNGY7QdpUS","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01RtxfciffSfDqSmMdq2KCDT","name":"Bash","input":{"command":"cd \"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\" && python -c \"\nimport pandas as pd\nfrom data_processing.diagnosis_lookup import assign_drug_indications, load_drug_indication_mapping\n\n_, st_to_frags = load_drug_indication_mapping()\n\n# Test tiebreaker with equal frequencies\ndf = pd.DataFrame({\n 'UPID': ['RMV444'],\n 'Drug Name': ['ADALIMUMAB'],\n 'PseudoNHSNoLinked': ['NHS444'],\n 'Directory': ['RHEUMATOLOGY'],\n})\n\ngp_matches_df = pd.DataFrame({\n 'PatientPseudonym': ['NHS444', 'NHS444'],\n 'Search_Term': ['psoriatic arthritis', 'crohn\\\\'s disease'],\n 'code_frequency': [5, 5], # Equal frequency\n})\n\nmodified_df, indication_df = assign_drug_indications(df, gp_matches_df, st_to_frags)\nupid = modified_df['UPID'].values[0]\n# Alphabetical: crohn's disease < psoriatic arthritis\nassert 'crohn' in upid, f'Equal freq should pick alphabetically first, got: {upid}'\nprint(f'OK: Equal frequency tiebreaker picks alphabetically: {upid}')\n\n# Test with empty gp_matches_df\ndf2 = pd.DataFrame({\n 'UPID': ['RMV555'],\n 'Drug Name': ['ADALIMUMAB'],\n 'PseudoNHSNoLinked': ['NHS555'],\n 'Directory': ['RHEUMATOLOGY'],\n})\nempty_gp = pd.DataFrame(columns=['PatientPseudonym', 'Search_Term', 'code_frequency'])\nmodified_df2, indication_df2 = assign_drug_indications(df2, empty_gp, st_to_frags)\nupid2 = modified_df2['UPID'].values[0]\nassert '(no GP dx)' in upid2, f'Empty GP matches should fallback, got: {upid2}'\nprint(f'OK: Empty GP matches falls back: {upid2}')\n\nprint('ALL EDGE CASE TESTS PASSED')\n\"\n","description":"Test tiebreaker edge cases","timeout":30000}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":1802,"cache_read_input_tokens":123378,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":1802},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"97aca897-46ea-4452-b916-2ed1a8b94a3e"}
{"type":"user","message":{"role":"user","content":[{"type":"tool_result","content":"Exit code 1\nTraceback (most recent call last):\r\n File \"\", line 24, in \r\n assert 'crohn' in upid, f'Equal freq should pick alphabetically first, got: {upid}'\r\n ^^^^^^^^^^^^^^^\r\nAssertionError: Equal freq should pick alphabetically first, got: RMV444|psoriatic arthritis","is_error":true,"tool_use_id":"toolu_01RtxfciffSfDqSmMdq2KCDT"}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"5a8912ee-eb59-4324-99ba-bf0b52397d19","tool_use_result":"Error: Exit code 1\nTraceback (most recent call last):\r\n File \"\", line 24, in \r\n assert 'crohn' in upid, f'Equal freq should pick alphabetically first, got: {upid}'\r\n ^^^^^^^^^^^^^^^\r\nAssertionError: Equal freq should pick alphabetically first, got: RMV444|psoriatic arthritis"}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01Pcr6pW9yXmjSuGVpw5m3tE","type":"message","role":"assistant","content":[{"type":"text","text":"The alphabetical tiebreaker is comparing with `(-freq, term)` ÔÇö so for equal freq, \"crohn's disease\" < \"psoriatic arthritis\" alphabetically, which means crohn's should come first. But the apostrophe in \"crohn's disease\" might be causing a sorting issue. Let me check."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":784,"cache_read_input_tokens":125180,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":784},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"6647c968-af63-4ceb-b400-140a1d0ed4af"}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01Pcr6pW9yXmjSuGVpw5m3tE","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_011s1TqAshDfxV7jJEcqSJ6p","name":"Bash","input":{"command":"cd \"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\" && python -c \"\nterms = [\\\"crohn's disease\\\", 'psoriatic arthritis']\nprint(sorted(terms))\n# crohn's has an apostrophe - let's see\nprint(repr(\\\"crohn's disease\\\" < 'psoriatic arthritis'))\n\"\n","description":"Check alphabetical sorting of crohn's vs psoriatic"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":784,"cache_read_input_tokens":125180,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":784},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"0fb301ba-acc6-4669-b17f-787127d637d4"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_011s1TqAshDfxV7jJEcqSJ6p","type":"tool_result","content":"[\"crohn's disease\", 'psoriatic arthritis']\r\nTrue","is_error":false}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"91b17186-8974-4d83-9916-1f13cf784fbb","tool_use_result":{"stdout":"[\"crohn's disease\", 'psoriatic arthritis']\r\nTrue\r","stderr":"","interrupted":false,"isImage":false}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01NMPEXnVdc7mKdCd1HD9Ssj","type":"message","role":"assistant","content":[{"type":"text","text":"Hmm, \"crohn's disease\" IS alphabetically first. Let me debug what's happening in the function."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":269,"cache_read_input_tokens":125964,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":269},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"2c938ca7-69a9-4d7e-af21-a68bf6292439"}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01NMPEXnVdc7mKdCd1HD9Ssj","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_014EHzCJRyzhqvjKDfSywfX2","name":"Bash","input":{"command":"cd \"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\" && python -c \"\nimport pandas as pd\nfrom data_processing.diagnosis_lookup import assign_drug_indications, load_drug_indication_mapping, get_search_terms_for_drug\n\n_, st_to_frags = load_drug_indication_mapping()\n\n# Check which Search_Terms ADALIMUMAB matches\nterms = get_search_terms_for_drug('ADALIMUMAB', st_to_frags)\nprint(f'ADALIMUMAB matches: {terms}')\n\n# Which of these overlap with our GP matches?\ngp_terms = {'psoriatic arthritis': 5, \\\"crohn's disease\\\": 5}\noverlap = {t: gp_terms[t] for t in terms if t in gp_terms}\nprint(f'Overlap with GP: {overlap}')\nprint(f'Sorted: {sorted(overlap.items(), key=lambda x: (-x[1], x[0]))}')\n\"\n","description":"Debug ADALIMUMAB matching overlap","timeout":15000}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":269,"cache_read_input_tokens":125964,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":269},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"08df5bf1-5e2e-4b79-a29b-71eb279043c0"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_014EHzCJRyzhqvjKDfSywfX2","type":"tool_result","content":"ADALIMUMAB matches: ['ankylosing spondylitis', 'axial spondyloarthritis', 'plaque psoriasis', 'psoriatic arthritis', 'rheumatoid arthritis', 'ulcerative colitis', 'uveitis']\r\nOverlap with GP: {'psoriatic arthritis': 5}\r\nSorted: [('psoriatic arthritis', 5)]","is_error":false}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"ff815cfb-434f-4f1a-9a6d-b55f85db87ed","tool_use_result":{"stdout":"ADALIMUMAB matches: ['ankylosing spondylitis', 'axial spondyloarthritis', 'plaque psoriasis', 'psoriatic arthritis', 'rheumatoid arthritis', 'ulcerative colitis', 'uveitis']\r\nOverlap with GP: {'psoriatic arthritis': 5}\r\nSorted: [('psoriatic arthritis', 5)]\r","stderr":"","interrupted":false,"isImage":false}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01Y82A3ViMZ672D738Md6SX8","type":"message","role":"assistant","content":[{"type":"text","text":"I see the issue. \"crohn's disease\" from DimSearchTerm.csv is not in the ADALIMUMAB Search_Terms list ÔÇö looking at the output, ADALIMUMAB matches: ankylosing spondylitis, axial spondyloarthritis, plaque psoriasis, psoriatic arthritis, rheumatoid arthritis, ulcerative colitis, uveitis. \"crohn's disease\" is NOT in that list (ADALIMUMAB doesn't match crohn's in DimSearchTerm.csv). So only psoriatic arthritis is in the intersection, giving a single match ÔÇö not a tiebreaker.\n\nMy test was wrong about the data. Let me fix the test to use two Search_Terms that actually overlap with ADALIMUMAB."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":684,"cache_read_input_tokens":126233,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":684},"output_tokens":6,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"90ea751a-d887-487e-82db-1010611e6f58"}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01Y82A3ViMZ672D738Md6SX8","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01UhphCkaSdqjf7hCr1jE1Gk","name":"Bash","input":{"command":"cd \"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\" && python -c \"\nimport pandas as pd\nfrom data_processing.diagnosis_lookup import assign_drug_indications, load_drug_indication_mapping, get_search_terms_for_drug\n\n_, st_to_frags = load_drug_indication_mapping()\n\n# Use two Search_Terms that ADALIMUMAB actually matches\n# Both psoriatic arthritis and rheumatoid arthritis\ndf = pd.DataFrame({\n 'UPID': ['RMV444'],\n 'Drug Name': ['ADALIMUMAB'],\n 'PseudoNHSNoLinked': ['NHS444'],\n 'Directory': ['RHEUMATOLOGY'],\n})\n\ngp_matches_df = pd.DataFrame({\n 'PatientPseudonym': ['NHS444', 'NHS444'],\n 'Search_Term': ['psoriatic arthritis', 'rheumatoid arthritis'],\n 'code_frequency': [5, 5], # Equal frequency\n})\n\nmodified_df, indication_df = assign_drug_indications(df, gp_matches_df, st_to_frags)\nupid = modified_df['UPID'].values[0]\n# Alphabetical: psoriatic arthritis < rheumatoid arthritis\nassert 'psoriatic arthritis' in upid, f'Equal freq should pick alphabetically first (psoriatic < rheumatoid), got: {upid}'\nprint(f'OK: Equal frequency tiebreaker picks alphabetically: {upid}')\n\n# Test different frequencies ÔÇö higher wins\ngp_matches_df2 = pd.DataFrame({\n 'PatientPseudonym': ['NHS444', 'NHS444'],\n 'Search_Term': ['psoriatic arthritis', 'rheumatoid arthritis'],\n 'code_frequency': [3, 47], # RA has higher frequency\n})\nmodified_df2, _ = assign_drug_indications(df, gp_matches_df2, st_to_frags)\nupid2 = modified_df2['UPID'].values[0]\nassert 'rheumatoid arthritis' in upid2, f'Higher freq should win, got: {upid2}'\nprint(f'OK: Higher frequency wins: {upid2}')\n\n# Test empty gp_matches\nempty_gp = pd.DataFrame(columns=['PatientPseudonym', 'Search_Term', 'code_frequency'])\nmodified_df3, indication_df3 = assign_drug_indications(df, empty_gp, st_to_frags)\nupid3 = modified_df3['UPID'].values[0]\nassert '(no GP dx)' in upid3, f'Empty GP should fallback, got: {upid3}'\nprint(f'OK: Empty GP falls back: {upid3}')\n\nprint('ALL TIEBREAKER TESTS PASSED')\n\"\n","description":"Corrected tiebreaker edge case tests","timeout":30000}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":684,"cache_read_input_tokens":126233,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":684},"output_tokens":6,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"8c471964-10af-432e-b70e-561cc43ffb52"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01UhphCkaSdqjf7hCr1jE1Gk","type":"tool_result","content":"OK: Equal frequency tiebreaker picks alphabetically: RMV444|psoriatic arthritis\r\nOK: Higher frequency wins: RMV444|rheumatoid arthritis\r\nOK: Empty GP falls back: RMV444|RHEUMATOLOGY (no GP dx)\r\nALL TIEBREAKER TESTS PASSED","is_error":false}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"0ba58eaa-a80a-4060-9109-56a6b5ba04a0","tool_use_result":{"stdout":"OK: Equal frequency tiebreaker picks alphabetically: RMV444|psoriatic arthritis\r\nOK: Higher frequency wins: RMV444|rheumatoid arthritis\r\nOK: Empty GP falls back: RMV444|RHEUMATOLOGY (no GP dx)\r\nALL TIEBREAKER TESTS PASSED\r","stderr":"","interrupted":false,"isImage":false}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01XzAZrMNdnnaFtJpHkdt6rg","type":"message","role":"assistant","content":[{"type":"text","text":"All tests pass:\n- Equal frequency  alphabetical tiebreaker works (\"psoriatic arthritis\" < \"rheumatoid arthritis\")\n- Higher frequency wins (47 RA codes vs 3 psoriatic codes  RA)\n- Empty GP matches  fallback to directory\n\nNow let me update the IMPLEMENTATION_PLAN.md to mark Task 2.1 and 2.2 complete, then commit and update progress.txt."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":1076,"cache_read_input_tokens":126917,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":1076},"output_tokens":4,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"b0bb082d-24d3-4b57-a07b-de399694bdcd"}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01XzAZrMNdnnaFtJpHkdt6rg","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01GVzyhTEvB42qJTVYzBQXoU","name":"Read","input":{"file_path":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\IMPLEMENTATION_PLAN.md","offset":107,"limit":40}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":1076,"cache_read_input_tokens":126917,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":1076},"output_tokens":4,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"f9622e0d-d50a-43e2-80f1-20f94464f440"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01GVzyhTEvB42qJTVYzBQXoU","type":"tool_result","content":" 107## Phase 2: Drug-Aware Indication Matching Logic\n 108\n 109### 2.1 Create `assign_drug_indications()` function\n 110- [ ] Add to `diagnosis_lookup.py` or `pathway_pipeline.py`:\n 111 ```\n 112 def assign_drug_indications(\n 113 df: pd.DataFrame, # HCD data with UPID, Drug Name columns\n 114 gp_matches_df: pd.DataFrame, # PatientPseudonym  list of matched Search_Terms\n 115 drug_mapping: dict, # From load_drug_indication_mapping()\n 116 ) -> tuple[pd.DataFrame, pd.DataFrame]:\n 117 Returns: (modified_df, indication_df)\n 118 - modified_df: HCD data with UPID replaced by {UPID}|{indication}\n 119 - indication_df: mapping modified_UPID  Search_Term\n 120 ```\n 121- [ ] Logic per UPID + Drug Name pair:\n 122 1. Get patient's GP-matched Search_Terms with code_frequency (from gp_matches_df via PseudoNHSNoLinked)\n 123 2. Get which Search_Terms include this drug (from drug_mapping)\n 124 3. Intersection = valid indications for this drug-patient pair\n 125 4. If 1 match: use it\n 126 5. If multiple matches: use highest code_frequency as tiebreaker (most GP coding activity = most likely treatment indication)\n 127 6. If 0 matches: use fallback directory\n 128- [ ] Modify UPID in df rows: `{original_UPID}|{matched_search_term}`\n 129- [ ] Build indication_df: `{modified_UPID}`  `Search_Term` (or fallback label)\n 130- [ ] Verify: Function compiles, handles edge cases (no GP match, no drug match)\n 131\n 132### 2.2 Handle tiebreaker for multiple indication matches\n 133- [ ] When a drug matches multiple Search_Terms AND patient has GP dx for multiple:\n 134 - Use `code_frequency` from the GP query (COUNT of matching SNOMED codes per Search_Term)\n 135 - Higher code_frequency = more clinical activity for that condition = more likely treatment indication\n 136 - E.g., patient with 47 RA codes and 2 crohn's codes  ADALIMUMAB assigned to RA\n 137 - code_frequency is already returned by the updated query in Task 1.1\n 138- [ ] Verify: Tiebreaker logic correctly picks highest-frequency diagnosis\n 139- [ ] Verify: Tie on frequency (rare but possible) falls back to alphabetical Search_Term for determinism\n 140\n 141---\n 142\n 143## Phase 3: Pipeline Integration\n 144\n 145### 3.1 Update `refresh_pathways.py` indication processing\n 146- [ ] In the `elif current_chart_type == \"indication\":` block:\n\n\nWhenever 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.\n\n"}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"0ed84530-1d0c-4fab-9511-2e53d5ef22a0","tool_use_result":{"type":"text","file":{"filePath":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\IMPLEMENTATION_PLAN.md","content":"## Phase 2: Drug-Aware Indication Matching Logic\n\n### 2.1 Create `assign_drug_indications()` function\n- [ ] Add to `diagnosis_lookup.py` or `pathway_pipeline.py`:\n ```\n def assign_drug_indications(\n df: pd.DataFrame, # HCD data with UPID, Drug Name columns\n gp_matches_df: pd.DataFrame, # PatientPseudonym  list of matched Search_Terms\n drug_mapping: dict, # From load_drug_indication_mapping()\n ) -> tuple[pd.DataFrame, pd.DataFrame]:\n Returns: (modified_df, indication_df)\n - modified_df: HCD data with UPID replaced by {UPID}|{indication}\n - indication_df: mapping modified_UPID  Search_Term\n ```\n- [ ] Logic per UPID + Drug Name pair:\n 1. Get patient's GP-matched Search_Terms with code_frequency (from gp_matches_df via PseudoNHSNoLinked)\n 2. Get which Search_Terms include this drug (from drug_mapping)\n 3. Intersection = valid indications for this drug-patient pair\n 4. If 1 match: use it\n 5. If multiple matches: use highest code_frequency as tiebreaker (most GP coding activity = most likely treatment indication)\n 6. If 0 matches: use fallback directory\n- [ ] Modify UPID in df rows: `{original_UPID}|{matched_search_term}`\n- [ ] Build indication_df: `{modified_UPID}`  `Search_Term` (or fallback label)\n- [ ] Verify: Function compiles, handles edge cases (no GP match, no drug match)\n\n### 2.2 Handle tiebreaker for multiple indication matches\n- [ ] When a drug matches multiple Search_Terms AND patient has GP dx for multiple:\n - Use `code_frequency` from the GP query (COUNT of matching SNOMED codes per Search_Term)\n - Higher code_frequency = more clinical activity for that condition = more likely treatment indication\n - E.g., patient with 47 RA codes and 2 crohn's codes  ADALIMUMAB assigned to RA\n - code_frequency is already returned by the updated query in Task 1.1\n- [ ] Verify: Tiebreaker logic correctly picks highest-frequency diagnosis\n- [ ] Verify: Tie on frequency (rare but possible) falls back to alphabetical Search_Term for determinism\n\n---\n\n## Phase 3: Pipeline Integration\n\n### 3.1 Update `refresh_pathways.py` indication processing\n- [ ] In the `elif current_chart_type == \"indication\":` block:","numLines":40,"startLine":107,"totalLines":239}}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01EgXtAviW8SKdvgxLsfk1Br","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01DprQgdY3ovW1m5zvmxivSD","name":"Edit","input":{"replace_all":false,"file_path":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\IMPLEMENTATION_PLAN.md","old_string":"### 2.1 Create `assign_drug_indications()` function\n- [ ] Add to `diagnosis_lookup.py` or `pathway_pipeline.py`:\n ```\n def assign_drug_indications(\n df: pd.DataFrame, # HCD data with UPID, Drug Name columns\n gp_matches_df: pd.DataFrame, # PatientPseudonym  list of matched Search_Terms\n drug_mapping: dict, # From load_drug_indication_mapping()\n ) -> tuple[pd.DataFrame, pd.DataFrame]:\n Returns: (modified_df, indication_df)\n - modified_df: HCD data with UPID replaced by {UPID}|{indication}\n - indication_df: mapping modified_UPID  Search_Term\n ```\n- [ ] Logic per UPID + Drug Name pair:\n 1. Get patient's GP-matched Search_Terms with code_frequency (from gp_matches_df via PseudoNHSNoLinked)\n 2. Get which Search_Terms include this drug (from drug_mapping)\n 3. Intersection = valid indications for this drug-patient pair\n 4. If 1 match: use it\n 5. If multiple matches: use highest code_frequency as tiebreaker (most GP coding activity = most likely treatment indication)\n 6. If 0 matches: use fallback directory\n- [ ] Modify UPID in df rows: `{original_UPID}|{matched_search_term}`\n- [ ] Build indication_df: `{modified_UPID}`  `Search_Term` (or fallback label)\n- [ ] Verify: Function compiles, handles edge cases (no GP match, no drug match)\n\n### 2.2 Handle tiebreaker for multiple indication matches\n- [ ] When a drug matches multiple Search_Terms AND patient has GP dx for multiple:\n - Use `code_frequency` from the GP query (COUNT of matching SNOMED codes per Search_Term)\n - Higher code_frequency = more clinical activity for that condition = more likely treatment indication\n - E.g., patient with 47 RA codes and 2 crohn's codes  ADALIMUMAB assigned to RA\n - code_frequency is already returned by the updated query in Task 1.1\n- [ ] Verify: Tiebreaker logic correctly picks highest-frequency diagnosis\n- [ ] Verify: Tie on frequency (rare but possible) falls back to alphabetical Search_Term for determinism","new_string":"### 2.1 Create `assign_drug_indications()` function\n- [x] Add to `diagnosis_lookup.py` or `pathway_pipeline.py`:\n ```\n def assign_drug_indications(\n df: pd.DataFrame, # HCD data with UPID, Drug Name columns\n gp_matches_df: pd.DataFrame, # PatientPseudonym  list of matched Search_Terms\n drug_mapping: dict, # From load_drug_indication_mapping()\n ) -> tuple[pd.DataFrame, pd.DataFrame]:\n Returns: (modified_df, indication_df)\n - modified_df: HCD data with UPID replaced by {UPID}|{indication}\n - indication_df: mapping modified_UPID  Search_Term\n ```\n- [x] Logic per UPID + Drug Name pair:\n 1. Get patient's GP-matched Search_Terms with code_frequency (from gp_matches_df via PseudoNHSNoLinked)\n 2. Get which Search_Terms include this drug (from drug_mapping)\n 3. Intersection = valid indications for this drug-patient pair\n 4. If 1 match: use it\n 5. If multiple matches: use highest code_frequency as tiebreaker (most GP coding activity = most likely treatment indication)\n 6. If 0 matches: use fallback directory\n- [x] Modify UPID in df rows: `{original_UPID}|{matched_search_term}`\n- [x] Build indication_df: `{modified_UPID}`  `Search_Term` (or fallback label)\n- [x] Verify: Function compiles, handles edge cases (no GP match, no drug match)\n\n### 2.2 Handle tiebreaker for multiple indication matches\n- [x] When a drug matches multiple Search_Terms AND patient has GP dx for multiple:\n - Use `code_frequency` from the GP query (COUNT of matching SNOMED codes per Search_Term)\n - Higher code_frequency = more clinical activity for that condition = more likely treatment indication\n - E.g., patient with 47 RA codes and 2 crohn's codes  ADALIMUMAB assigned to RA\n - code_frequency is already returned by the updated query in Task 1.1\n- [x] Verify: Tiebreaker logic correctly picks highest-frequency diagnosis\n- [x] Verify: Tie on frequency (rare but possible) falls back to alphabetical Search_Term for determinism"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":1087,"cache_read_input_tokens":127993,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":1087},"output_tokens":25,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"f015b75f-3e00-46a7-be92-f01245f9d970"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01DprQgdY3ovW1m5zvmxivSD","type":"tool_result","content":"The file C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\IMPLEMENTATION_PLAN.md has been updated successfully."}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"4fb0ea08-8d93-45a3-805b-00c0e317d887","tool_use_result":{"filePath":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\IMPLEMENTATION_PLAN.md","oldString":"### 2.1 Create `assign_drug_indications()` function\n- [ ] Add to `diagnosis_lookup.py` or `pathway_pipeline.py`:\n ```\n def assign_drug_indications(\n df: pd.DataFrame, # HCD data with UPID, Drug Name columns\n gp_matches_df: pd.DataFrame, # PatientPseudonym  list of matched Search_Terms\n drug_mapping: dict, # From load_drug_indication_mapping()\n ) -> tuple[pd.DataFrame, pd.DataFrame]:\n Returns: (modified_df, indication_df)\n - modified_df: HCD data with UPID replaced by {UPID}|{indication}\n - indication_df: mapping modified_UPID  Search_Term\n ```\n- [ ] Logic per UPID + Drug Name pair:\n 1. Get patient's GP-matched Search_Terms with code_frequency (from gp_matches_df via PseudoNHSNoLinked)\n 2. Get which Search_Terms include this drug (from drug_mapping)\n 3. Intersection = valid indications for this drug-patient pair\n 4. If 1 match: use it\n 5. If multiple matches: use highest code_frequency as tiebreaker (most GP coding activity = most likely treatment indication)\n 6. If 0 matches: use fallback directory\n- [ ] Modify UPID in df rows: `{original_UPID}|{matched_search_term}`\n- [ ] Build indication_df: `{modified_UPID}`  `Search_Term` (or fallback label)\n- [ ] Verify: Function compiles, handles edge cases (no GP match, no drug match)\n\n### 2.2 Handle tiebreaker for multiple indication matches\n- [ ] When a drug matches multiple Search_Terms AND patient has GP dx for multiple:\n - Use `code_frequency` from the GP query (COUNT of matching SNOMED codes per Search_Term)\n - Higher code_frequency = more clinical activity for that condition = more likely treatment indication\n - E.g., patient with 47 RA codes and 2 crohn's codes  ADALIMUMAB assigned to RA\n - code_frequency is already returned by the updated query in Task 1.1\n- [ ] Verify: Tiebreaker logic correctly picks highest-frequency diagnosis\n- [ ] Verify: Tie on frequency (rare but possible) falls back to alphabetical Search_Term for determinism","newString":"### 2.1 Create `assign_drug_indications()` function\n- [x] Add to `diagnosis_lookup.py` or `pathway_pipeline.py`:\n ```\n def assign_drug_indications(\n df: pd.DataFrame, # HCD data with UPID, Drug Name columns\n gp_matches_df: pd.DataFrame, # PatientPseudonym  list of matched Search_Terms\n drug_mapping: dict, # From load_drug_indication_mapping()\n ) -> tuple[pd.DataFrame, pd.DataFrame]:\n Returns: (modified_df, indication_df)\n - modified_df: HCD data with UPID replaced by {UPID}|{indication}\n - indication_df: mapping modified_UPID  Search_Term\n ```\n- [x] Logic per UPID + Drug Name pair:\n 1. Get patient's GP-matched Search_Terms with code_frequency (from gp_matches_df via PseudoNHSNoLinked)\n 2. Get which Search_Terms include this drug (from drug_mapping)\n 3. Intersection = valid indications for this drug-patient pair\n 4. If 1 match: use it\n 5. If multiple matches: use highest code_frequency as tiebreaker (most GP coding activity = most likely treatment indication)\n 6. If 0 matches: use fallback directory\n- [x] Modify UPID in df rows: `{original_UPID}|{matched_search_term}`\n- [x] Build indication_df: `{modified_UPID}`  `Search_Term` (or fallback label)\n- [x] Verify: Function compiles, handles edge cases (no GP match, no drug match)\n\n### 2.2 Handle tiebreaker for multiple indication matches\n- [x] When a drug matches multiple Search_Terms AND patient has GP dx for multiple:\n - Use `code_frequency` from the GP query (COUNT of matching SNOMED codes per Search_Term)\n - Higher code_frequency = more clinical activity for that condition = more likely treatment indication\n - E.g., patient with 47 RA codes and 2 crohn's codes  ADALIMUMAB assigned to RA\n - code_frequency is already returned by the updated query in Task 1.1\n- [x] Verify: Tiebreaker logic correctly picks highest-frequency diagnosis\n- [x] Verify: Tie on frequency (rare but possible) falls back to alphabetical Search_Term for determinism","originalFile":"# Implementation Plan - Drug-Aware Indication Matching\n\n## Project Overview\n\nUpdate 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.\n\n### The Problem\n\nA patient on ADALIMUMAB + OMALIZUMAB currently gets assigned a single indication (e.g., \"rheumatoid arthritis\"  the most recent GP match). But:\n- ADALIMUMAB is used for rheumatoid arthritis, axial spondyloarthritis, crohn's disease, etc.\n- OMALIZUMAB is used for asthma, allergic asthma, urticaria\n\nThese are different clinical pathways and should be treated as separate treatment journeys.\n\n### The Solution\n\nMatch each drug to an indication by cross-referencing:\n1. **GP diagnosis**  which Search_Terms the patient has matching SNOMED codes for\n2. **Drug mapping**  which Search_Terms list each drug (from `DimSearchTerm.csv`)\n\nOnly 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).\n\n### Key Design Decisions\n\n| Aspect | Decision |\n|--------|----------|\n| Drug-indication source | `data/DimSearchTerm.csv`  Search_Term  CleanedDrugName mapping |\n| UPID modification | `{original_UPID}\\|{search_term}` for drugs with matched indication |\n| GP diagnosis matching | Return ALL matches per patient (not just most recent) |\n| Drug matching | Substring match: HCD drug name contains DimSearchTerm fragment |\n| Multiple indication matches per drug | Use highest GP code frequency as tiebreaker (COUNT of matching SNOMED codes per Search_Term) |\n| GP code time range | Only codes from MIN(Intervention Date) onwards  restricts to HCD data window |\n| No indication match | Fallback to directory (same as current behavior) |\n| Same patient, different indications | Separate pathways via different modified UPIDs |\n\n### Examples\n\n**Patient on ADALIMUMAB + GOLIMUMAB, GP dx: axial spondyloarthritis + asthma**\n- axial spondyloarthritis drug list includes both ADALIMUMAB and GOLIMUMAB\n-  Both drugs grouped under \"axial spondyloarthritis\", single pathway\n- Modified UPID: `RMV12345|axial spondyloarthritis`\n\n**Patient on ADALIMUMAB + OMALIZUMAB, GP dx: axial spondyloarthritis + asthma**\n- axial spondyloarthritis lists ADALIMUMAB but not OMALIZUMAB\n- asthma lists OMALIZUMAB but not ADALIMUMAB\n-  Two separate pathways:\n - `RMV12345|axial spondyloarthritis` with ADALIMUMAB\n - `RMV12345|asthma` with OMALIZUMAB\n\n**Patient on ADALIMUMAB, GP dx: rheumatoid arthritis (47 codes) + crohn's disease (2 codes)**\n- Both Search_Terms list ADALIMUMAB AND patient has GP dx for both\n-  Tiebreaker: highest code frequency  rheumatoid arthritis has 47 matching SNOMED codes vs 2 for crohn's\n-  Single pathway under rheumatoid arthritis (more clinical activity = more likely the treatment indication)\n\n---\n\n## Phase 1: Update Snowflake Query & Drug Mapping\n\n### 1.1 Update `get_patient_indication_groups()` to return ALL matches with frequency\n- [x] Modify the Snowflake query in `get_patient_indication_groups()` (diagnosis_lookup.py):\n - Remove `QUALIFY ROW_NUMBER() OVER (PARTITION BY ... ORDER BY EventDateTime DESC) = 1`\n - Return ALL matching Search_Terms per patient with code frequency:\n ```sql\n SELECT pc.\"PatientPseudonym\" AS \"PatientPseudonym\",\n aic.Search_Term AS \"Search_Term\",\n COUNT(*) AS \"code_frequency\"\n FROM PrimaryCareClinicalCoding pc\n JOIN AllIndicationCodes aic ON pc.\"SNOMEDCode\" = aic.SNOMEDCode\n WHERE pc.\"PatientPseudonym\" IN (...)\n AND pc.\"EventDateTime\" >= :earliest_hcd_date\n GROUP BY pc.\"PatientPseudonym\", aic.Search_Term\n ```\n - `code_frequency` = number of matching SNOMED codes per Search_Term per patient\n - Higher frequency = more clinical activity = stronger signal for tiebreaker\n - `earliest_hcd_date` = `MIN(Intervention Date)` from the HCD DataFrame  restricts GP codes to the HCD data window, reducing noise from old/irrelevant diagnoses\n- [x] Accept `earliest_hcd_date` parameter in `get_patient_indication_groups()` and pass to query\n- [x] Keep batch processing (500 patients per query)\n- [x] Update return type: DataFrame now has multiple rows per patient (PatientPseudonym, Search_Term, code_frequency)\n- [ ] Verify: Query returns more rows than before (patients with multiple matching diagnoses) *(requires live Snowflake  will be verified in Phase 3/4)*\n\n### 1.2 Merge related asthma Search_Terms in CLUSTER_MAPPING_SQL\n- [x] In `CLUSTER_MAPPING_SQL` (diagnosis_lookup.py), merge these 3 Search_Terms into one `\"asthma\"` entry:\n - `allergic asthma` (Cluster: OMALIZUMAB only)\n - `asthma` (Cluster: BENRALIZUMAB, DUPILUMAB, INHALED, MEPOLIZUMAB, OMALIZUMAB, RESLIZUMAB)\n - `severe persistent allergic asthma` (Cluster: OMALIZUMAB only)\n- [x] Map all 3 Cluster_IDs to `Search_Term = 'asthma'` in the CTE VALUES\n- [x] `urticaria` (OMALIZUMAB, DERMATOLOGY) stays SEPARATE  do NOT merge with asthma\n- [x] Also update `load_drug_indication_mapping()` to apply the same merge when loading DimSearchTerm.csv:\n - Combine drug lists from all 3 entries under a single `\"asthma\"` key\n - Deduplicate drug fragments (OMALIZUMAB appears in all 3)\n- [x] Verify: GP code lookup returns `\"asthma\"` (not `\"allergic asthma\"` or `\"severe persistent allergic asthma\"`)\n- [x] Verify: Drug mapping for `\"asthma\"` includes full combined drug list: BENRALIZUMAB, DUPILUMAB, INHALED, MEPOLIZUMAB, OMALIZUMAB, RESLIZUMAB\n\n### 1.3 Build drug-to-Search_Term lookup from DimSearchTerm.csv\n- [x] Add function `load_drug_indication_mapping()` to `diagnosis_lookup.py`:\n - Loads `data/DimSearchTerm.csv`\n - Builds dict: `drug_fragment (uppercase)  list[Search_Term]`\n - Also builds reverse: `search_term  list[drug_fragments]`\n - CleanedDrugName is pipe-separated (e.g., \"ADALIMUMAB|GOLIMUMAB|IXEKIZUMAB\")\n- [x] Add function `get_search_terms_for_drug(drug_name, search_term_to_fragments) -> list[str]`:\n - Returns all Search_Terms whose drug fragments are substrings of the drug name (case-insensitive)\n - More practical than per-term boolean check  returns all matches at once for Phase 2 use\n- [x] Verify: ADALIMUMAB matches \"axial spondyloarthritis\", OMALIZUMAB matches \"asthma\"\n\n---\n\n## Phase 2: Drug-Aware Indication Matching Logic\n\n### 2.1 Create `assign_drug_indications()` function\n- [ ] Add to `diagnosis_lookup.py` or `pathway_pipeline.py`:\n ```\n def assign_drug_indications(\n df: pd.DataFrame, # HCD data with UPID, Drug Name columns\n gp_matches_df: pd.DataFrame, # PatientPseudonym  list of matched Search_Terms\n drug_mapping: dict, # From load_drug_indication_mapping()\n ) -> tuple[pd.DataFrame, pd.DataFrame]:\n Returns: (modified_df, indication_df)\n - modified_df: HCD data with UPID replaced by {UPID}|{indication}\n - indication_df: mapping modified_UPID  Search_Term\n ```\n- [ ] Logic per UPID + Drug Name pair:\n 1. Get patient's GP-matched Search_Terms with code_frequency (from gp_matches_df via PseudoNHSNoLinked)\n 2. Get which Search_Terms include this drug (from drug_mapping)\n 3. Intersection = valid indications for this drug-patient pair\n 4. If 1 match: use it\n 5. If multiple matches: use highest code_frequency as tiebreaker (most GP coding activity = most likely treatment indication)\n 6. If 0 matches: use fallback directory\n- [ ] Modify UPID in df rows: `{original_UPID}|{matched_search_term}`\n- [ ] Build indication_df: `{modified_UPID}`  `Search_Term` (or fallback label)\n- [ ] Verify: Function compiles, handles edge cases (no GP match, no drug match)\n\n### 2.2 Handle tiebreaker for multiple indication matches\n- [ ] When a drug matches multiple Search_Terms AND patient has GP dx for multiple:\n - Use `code_frequency` from the GP query (COUNT of matching SNOMED codes per Search_Term)\n - Higher code_frequency = more clinical activity for that condition = more likely treatment indication\n - E.g., patient with 47 RA codes and 2 crohn's codes  ADALIMUMAB assigned to RA\n - code_frequency is already returned by the updated query in Task 1.1\n- [ ] Verify: Tiebreaker logic correctly picks highest-frequency diagnosis\n- [ ] Verify: Tie on frequency (rare but possible) falls back to alphabetical Search_Term for determinism\n\n---\n\n## Phase 3: Pipeline Integration\n\n### 3.1 Update `refresh_pathways.py` indication processing\n- [ ] In the `elif current_chart_type == \"indication\":` block:\n 1. Call `get_patient_indication_groups()` as before (but now returns ALL matches)\n 2. Load drug mapping: `drug_mapping = load_drug_indication_mapping()`\n 3. Call `assign_drug_indications(df, gp_matches_df, drug_mapping)`\n 4. Use modified_df (with indication-aware UPIDs) for pathway processing\n 5. Use indication_df for the indication mapping\n- [ ] Pass modified_df (not original df) to `process_indication_pathway_for_date_filter()`\n- [ ] Verify: Pipeline compiles, `python -m py_compile cli/refresh_pathways.py`\n\n### 3.2 Test with dry run\n- [ ] Run `python -m cli.refresh_pathways --chart-type indication --dry-run -v`\n- [ ] Verify:\n - Modified UPIDs appear in pipeline log (e.g., `RMV12345|rheumatoid arthritis`)\n - Patient counts are reasonable (will be higher than before since same patient can appear under multiple indications)\n - Drug-indication matching is logged (match rate, fallback rate)\n - Pathway hierarchy shows drug-specific grouping under correct indications\n\n---\n\n## Phase 4: Full Refresh & Validation\n\n### 4.1 Full refresh with both chart types\n- [ ] Run `python -m cli.refresh_pathways --chart-type all`\n- [ ] Verify:\n - Both chart types generate data\n - Directory charts unchanged (no modified UPIDs)\n - Indication charts reflect drug-aware matching\n\n### 4.2 Validate indication chart correctness\n- [ ] Check that drugs under an indication all appear in that Search_Term's drug list\n- [ ] Verify that a patient on drugs for different indications creates separate pathway branches\n- [ ] Verify that drugs sharing an indication are grouped in the same pathway\n- [ ] Log: patient count comparison (old vs new approach)\n\n### 4.3 Validate Reflex UI\n- [ ] Run `python -m reflex compile` to verify app compiles\n- [ ] Verify chart type toggle still works\n- [ ] Verify indication chart shows correct hierarchy\n\n---\n\n## Completion Criteria\n\nAll tasks marked `[x]` AND:\n- [ ] App compiles without errors (`reflex compile` succeeds)\n- [ ] Both chart types generate pathway data\n- [ ] Indication charts show drug-specific indication matching\n- [ ] Drugs under the same indication for the same patient are in one pathway\n- [ ] Drugs under different indications for the same patient create separate pathways\n- [ ] Fallback works for drugs with no indication match\n- [ ] Full refresh completes successfully\n- [ ] Existing directory charts are unaffected\n\n---\n\n## Reference\n\n### DimSearchTerm.csv Structure\n```\nSearch_Term,CleanedDrugName,PrimaryDirectorate\nrheumatoid arthritis,ABATACEPT|ADALIMUMAB|ANAKINRA|BARICITINIB|...,RHEUMATOLOGY\nasthma,BENRALIZUMAB|DUPILUMAB|INHALED|MEPOLIZUMAB|OMALIZUMAB|RESLIZUMAB,THORACIC MEDICINE\n```\n\n### Modified UPID Format\n```\nOriginal: RMV12345\nModified: RMV12345|rheumatoid arthritis\nFallback: RMV12345|RHEUMATOLOGY (no GP dx)\n```\n\n### Current vs New Indication Flow\n```\nCURRENT:\n Patient  GP dx (most recent)  single Search_Term  one pathway\n\nNEW:\n Patient + Drug A  GP dx matching Drug A  Search_Term X\n Patient + Drug B  GP dx matching Drug B  Search_Term Y\n  If X == Y: one pathway under X\n  If X != Y: two pathways (modified UPIDs)\n```\n\n### Key Files\n\n| File | Changes |\n|------|---------|\n| `data_processing/diagnosis_lookup.py` | Update query, add drug mapping functions |\n| `data_processing/pathway_pipeline.py` | Possibly minor changes for modified UPIDs |\n| `cli/refresh_pathways.py` | Integrate drug-aware matching into pipeline |\n| `data/DimSearchTerm.csv` | Reference data (read-only) |\n| `analysis/pathway_analyzer.py` | No changes expected (UPID changes are transparent) |\n| `pathways_app/pathways_app.py` | No changes expected |\n","structuredPatch":[{"oldStart":107,"oldLines":7,"newStart":107,"newLines":7,"lines":[" ## Phase 2: Drug-Aware Indication Matching Logic"," "," ### 2.1 Create `assign_drug_indications()` function","-- [ ] Add to `diagnosis_lookup.py` or `pathway_pipeline.py`:","+- [x] Add to `diagnosis_lookup.py` or `pathway_pipeline.py`:"," ```"," def assign_drug_indications("," df: pd.DataFrame, # HCD data with UPID, Drug Name columns"]},{"oldStart":118,"oldLines":25,"newStart":118,"newLines":25,"lines":[" - modified_df: HCD data with UPID replaced by {UPID}|{indication}"," - indication_df: mapping modified_UPID  Search_Term"," ```","-- [ ] Logic per UPID + Drug Name pair:","+- [x] 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)","+- [x] Modify UPID in df rows: `{original_UPID}|{matched_search_term}`","+- [x] Build indication_df: `{modified_UPID}`  `Search_Term` (or fallback label)","+- [x] 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:","+- [x] 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","+- [x] Verify: Tiebreaker logic correctly picks highest-frequency diagnosis","+- [x] Verify: Tie on frequency (rare but possible) falls back to alphabetical Search_Term for determinism"," "," ---"," "]}],"userModified":false,"replaceAll":false}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_014cMjfz5Paspg6WPH13iNNG","type":"message","role":"assistant","content":[{"type":"text","text":"Now commit the changes."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":1369,"cache_read_input_tokens":129080,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":1369},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"f3987f79-1638-4dbe-9d5b-cd9a9ecd99ed"}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_014cMjfz5Paspg6WPH13iNNG","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_014fU6TWEE47EyP9BGGefTQf","name":"TodoWrite","input":{"todos":[{"content":"Read project files (progress.txt, IMPLEMENTATION_PLAN.md, guardrails.md)","status":"completed","activeForm":"Reading project files"},{"content":"Build assign_drug_indications() function (Task 2.1 + 2.2)","status":"completed","activeForm":"Building assign_drug_indications() function"},{"content":"Validate code (py_compile, import check, mock data test)","status":"completed","activeForm":"Validating code"},{"content":"Commit and update progress.txt","status":"in_progress","activeForm":"Committing and updating progress"}]}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":1369,"cache_read_input_tokens":129080,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":1369},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"f454e6fc-ed81-4ad6-be7b-f39106d4d389"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_014fU6TWEE47EyP9BGGefTQf","type":"tool_result","content":"Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable"}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"4d87d538-587c-49c1-b598-fbe4bc19623f","tool_use_result":{"oldTodos":[{"content":"Read project files (progress.txt, IMPLEMENTATION_PLAN.md, guardrails.md)","status":"completed","activeForm":"Reading project files"},{"content":"Build assign_drug_indications() function (Task 2.1 + 2.2)","status":"completed","activeForm":"Building assign_drug_indications() function"},{"content":"Validate code (py_compile, import check, mock data test)","status":"in_progress","activeForm":"Validating code"},{"content":"Commit and update progress.txt","status":"pending","activeForm":"Committing and updating progress"}],"newTodos":[{"content":"Read project files (progress.txt, IMPLEMENTATION_PLAN.md, guardrails.md)","status":"completed","activeForm":"Reading project files"},{"content":"Build assign_drug_indications() function (Task 2.1 + 2.2)","status":"completed","activeForm":"Building assign_drug_indications() function"},{"content":"Validate code (py_compile, import check, mock data test)","status":"completed","activeForm":"Validating code"},{"content":"Commit and update progress.txt","status":"in_progress","activeForm":"Committing and updating progress"}]}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01GpHzjMT8YAbRU546a5fNZR","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01RdxBpGodKEhsHHqBuBosJq","name":"Bash","input":{"command":"cd \"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\" && git add data_processing/diagnosis_lookup.py IMPLEMENTATION_PLAN.md && git commit -m \"$(cat <<'EOF'\nfeat: add assign_drug_indications() for drug-aware indication matching (Task 2.1 + 2.2)\nEOF\n)\"","description":"Commit drug-indication matching function"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":259,"cache_read_input_tokens":130449,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":259},"output_tokens":25,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"ae839dcf-d042-4d6a-a254-e4080c5e5b9b"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01RdxBpGodKEhsHHqBuBosJq","type":"tool_result","content":"[feature/snomed-indication-mapping 408976e] feat: add assign_drug_indications() for drug-aware indication matching (Task 2.1 + 2.2)\n 2 files changed, 179 insertions(+), 8 deletions(-)","is_error":false}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"7c1b6a13-be38-44ee-bece-5288a8dbeae4","tool_use_result":{"stdout":"[feature/snomed-indication-mapping 408976e] feat: add assign_drug_indications() for drug-aware indication matching (Task 2.1 + 2.2)\n 2 files changed, 179 insertions(+), 8 deletions(-)\r","stderr":"","interrupted":false,"isImage":false}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01GHWoNU2Pccnq196JTFKKwR","type":"message","role":"assistant","content":[{"type":"text","text":"Now update progress.txt with the iteration log."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":235,"cache_read_input_tokens":130708,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":235},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"007baf33-ee24-4e76-88c0-e39c0601312b"}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01GHWoNU2Pccnq196JTFKKwR","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01W3QeJNk7G8AjN5bGNJCZSN","name":"Read","input":{"file_path":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\progress.txt","offset":193,"limit":5}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":235,"cache_read_input_tokens":130708,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":235},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"5fb05357-f162-4241-b2da-50ef2fa0f152"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01W3QeJNk7G8AjN5bGNJCZSN","type":"tool_result","content":" 193- The final Phase 1 subtask (1.1 verify with live Snowflake) will be tested during Phase 3/4 integration\n 194### Blocked items:\n 195- Task 1.1 final subtask \"Verify: Query returns more rows\" requires live Snowflake  deferred to Phase 3/4\n 196\n\n\nWhenever 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.\n\n"}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"023798ea-bbad-4ac3-9269-d7cfe8ff3d4d","tool_use_result":{"type":"text","file":{"filePath":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\progress.txt","content":"- The final Phase 1 subtask (1.1 verify with live Snowflake) will be tested during Phase 3/4 integration\n### Blocked items:\n- Task 1.1 final subtask \"Verify: Query returns more rows\" requires live Snowflake  deferred to Phase 3/4\n","numLines":4,"startLine":193,"totalLines":196}}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01TWYu7tHjVyBbvy5ZpZyv7s","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01FMSzTY2BkumFv5N9Rj6qcS","name":"Edit","input":{"replace_all":false,"file_path":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\progress.txt","old_string":"### Blocked items:\n- Task 1.1 final subtask \"Verify: Query returns more rows\" requires live Snowflake  deferred to Phase 3/4","new_string":"### Blocked items:\n- Task 1.1 final subtask \"Verify: Query returns more rows\" requires live Snowflake  deferred to Phase 3/4\n\n## Iteration 4  2026-02-05\n### Task: 2.1 + 2.2  Create assign_drug_indications() with tiebreaker logic\n### Why this task:\n- All Phase 1 dependencies complete (1.1 query returns ALL matches, 1.2 asthma merged, 1.3 drug mapping loaded)\n- Task 2.1 is the core matching function needed before Phase 3 pipeline integration\n- Task 2.2 (tiebreaker) is naturally part of 2.1  implemented together\n- Can be built and tested with mock data (no Snowflake needed)\n### Status: COMPLETE\n### What was done:\n- Added `assign_drug_indications()` to `diagnosis_lookup.py`:\n - Input: HCD df (with UPID, Drug Name, PseudoNHSNoLinked, Directory), gp_matches_df, search_term_to_fragments\n - Output: (modified_df with UPID|search_term, indication_df mapping modified_UPID  Search_Term)\n - Builds GP lookup: PseudoNHSNoLinked  {Search_Term: code_frequency}\n - Caches drugSearch_Term lookups to avoid recomputing per row\n - For each (UPID, Drug Name) pair:\n - Intersects drug's Search_Terms with patient's GP matches\n - Single match: use it\n - Multiple matches: highest code_frequency wins, alphabetical tiebreak\n - No match: fallback to \"{Directory} (no GP dx)\"\n - Applies modified UPIDs via df.apply() (vectorized lookup from cache)\n - Builds indication_df with unique modified UPID  Directory column\n - Comprehensive logging: match rate, tiebreaker count, fallback count, top 5 indications\n- Updated __all__ exports\n### Validation results:\n- Tier 1 (Code): py_compile PASSED, import check PASSED\n- Tier 2 (Data): Mock data tests ALL PASSED:\n - ADALIMUMAB + GP dx (RA + asthma)  matched to RA (drug mapping intersection)\n - OMALIZUMAB + GP dx (RA + asthma)  matched to asthma (drug mapping intersection)\n - ADALIMUMAB + GP dx (RA 3 freq + crohn's 2 freq)  tiebreaker picks RA\n - ADALIMUMAB + GP dx (psoriatic 5 freq + RA 5 freq)  alphabetical tiebreak picks psoriatic arthritis\n - Higher frequency (47 RA vs 3 psoriatic)  RA wins\n - No GP match  fallback to directory\n - Empty GP DataFrame  all fallback\n - Different drugs with different indications  different modified UPIDs\n- Tier 3 (Functional): N/A (no UI changes yet)\n### Files changed:\n- data_processing/diagnosis_lookup.py (added assign_drug_indications, updated __all__)\n- IMPLEMENTATION_PLAN.md (marked 2.1 and 2.2 subtasks [x])\n### Committed: 408976e \"feat: add assign_drug_indications() for drug-aware indication matching (Task 2.1 + 2.2)\"\n### Patterns discovered:\n- Function signature takes `search_term_to_fragments` (the second element from load_drug_indication_mapping())  NOT the full tuple. Callers must destructure: `_, st_to_frags = load_drug_indication_mapping()`\n- The function uses df.apply() to set modified UPIDs  for large DataFrames (656K rows), this could be slow. If performance is an issue in Phase 3, could vectorize with merge operations instead. But apply with cached lookup dict should be OK.\n- \"crohn's disease\" is NOT in ADALIMUMAB's DimSearchTerm mapping (ADALIMUMAB maps to: ankylosing spondylitis, axial spondyloarthritis, plaque psoriasis, psoriatic arthritis, rheumatoid arthritis, ulcerative colitis, uveitis). Initial test assumption was wrong.\n- indication_df has 'Directory' column (not 'Search_Term') for compatibility with generate_icicle_chart_indication() which expects indication_df.loc[upid, 'Directory']\n### Next iteration should:\n- Work on Task 3.1: Update `refresh_pathways.py` indication processing to use assign_drug_indications()\n - The current code at lines 424-428 uses `dict(zip(...))` which only keeps LAST match per patient  this must be replaced\n - Key changes in the `elif current_chart_type == \"indication\":` block:\n 1. Load drug mapping: `_, st_to_frags = load_drug_indication_mapping()`\n 2. Pass `earliest_hcd_date=df['Intervention Date'].min().strftime('%Y-%m-%d')` to get_patient_indication_groups()\n 3. Call `assign_drug_indications(df, gp_matches_df, st_to_frags)` to get (modified_df, indication_df)\n 4. Use modified_df (not original df) for pathway processing\n 5. indication_df is already in the right format (indexed by modified UPID, 'Directory' column)\n 6. Remove the old match_lookup/dict(zip) code and the manual indication_df building\n - Import assign_drug_indications and load_drug_indication_mapping at top of file\n - This replaces ~50 lines of the old approach with ~10 lines using the new function\n - Can verify with py_compile; full Snowflake test via --dry-run\n### Blocked items:\n- None"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":298,"cache_read_input_tokens":130943,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":298},"output_tokens":24,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"f45faff6-0237-46f0-a6f9-fcaac48268f9"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01FMSzTY2BkumFv5N9Rj6qcS","type":"tool_result","content":"The file C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\progress.txt has been updated successfully."}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"b8afa581-5f62-457f-854b-8cf013d18707","tool_use_result":{"filePath":"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\\progress.txt","oldString":"### Blocked items:\n- Task 1.1 final subtask \"Verify: Query returns more rows\" requires live Snowflake  deferred to Phase 3/4","newString":"### Blocked items:\n- Task 1.1 final subtask \"Verify: Query returns more rows\" requires live Snowflake  deferred to Phase 3/4\n\n## Iteration 4  2026-02-05\n### Task: 2.1 + 2.2  Create assign_drug_indications() with tiebreaker logic\n### Why this task:\n- All Phase 1 dependencies complete (1.1 query returns ALL matches, 1.2 asthma merged, 1.3 drug mapping loaded)\n- Task 2.1 is the core matching function needed before Phase 3 pipeline integration\n- Task 2.2 (tiebreaker) is naturally part of 2.1  implemented together\n- Can be built and tested with mock data (no Snowflake needed)\n### Status: COMPLETE\n### What was done:\n- Added `assign_drug_indications()` to `diagnosis_lookup.py`:\n - Input: HCD df (with UPID, Drug Name, PseudoNHSNoLinked, Directory), gp_matches_df, search_term_to_fragments\n - Output: (modified_df with UPID|search_term, indication_df mapping modified_UPID  Search_Term)\n - Builds GP lookup: PseudoNHSNoLinked  {Search_Term: code_frequency}\n - Caches drugSearch_Term lookups to avoid recomputing per row\n - For each (UPID, Drug Name) pair:\n - Intersects drug's Search_Terms with patient's GP matches\n - Single match: use it\n - Multiple matches: highest code_frequency wins, alphabetical tiebreak\n - No match: fallback to \"{Directory} (no GP dx)\"\n - Applies modified UPIDs via df.apply() (vectorized lookup from cache)\n - Builds indication_df with unique modified UPID  Directory column\n - Comprehensive logging: match rate, tiebreaker count, fallback count, top 5 indications\n- Updated __all__ exports\n### Validation results:\n- Tier 1 (Code): py_compile PASSED, import check PASSED\n- Tier 2 (Data): Mock data tests ALL PASSED:\n - ADALIMUMAB + GP dx (RA + asthma)  matched to RA (drug mapping intersection)\n - OMALIZUMAB + GP dx (RA + asthma)  matched to asthma (drug mapping intersection)\n - ADALIMUMAB + GP dx (RA 3 freq + crohn's 2 freq)  tiebreaker picks RA\n - ADALIMUMAB + GP dx (psoriatic 5 freq + RA 5 freq)  alphabetical tiebreak picks psoriatic arthritis\n - Higher frequency (47 RA vs 3 psoriatic)  RA wins\n - No GP match  fallback to directory\n - Empty GP DataFrame  all fallback\n - Different drugs with different indications  different modified UPIDs\n- Tier 3 (Functional): N/A (no UI changes yet)\n### Files changed:\n- data_processing/diagnosis_lookup.py (added assign_drug_indications, updated __all__)\n- IMPLEMENTATION_PLAN.md (marked 2.1 and 2.2 subtasks [x])\n### Committed: 408976e \"feat: add assign_drug_indications() for drug-aware indication matching (Task 2.1 + 2.2)\"\n### Patterns discovered:\n- Function signature takes `search_term_to_fragments` (the second element from load_drug_indication_mapping())  NOT the full tuple. Callers must destructure: `_, st_to_frags = load_drug_indication_mapping()`\n- The function uses df.apply() to set modified UPIDs  for large DataFrames (656K rows), this could be slow. If performance is an issue in Phase 3, could vectorize with merge operations instead. But apply with cached lookup dict should be OK.\n- \"crohn's disease\" is NOT in ADALIMUMAB's DimSearchTerm mapping (ADALIMUMAB maps to: ankylosing spondylitis, axial spondyloarthritis, plaque psoriasis, psoriatic arthritis, rheumatoid arthritis, ulcerative colitis, uveitis). Initial test assumption was wrong.\n- indication_df has 'Directory' column (not 'Search_Term') for compatibility with generate_icicle_chart_indication() which expects indication_df.loc[upid, 'Directory']\n### Next iteration should:\n- Work on Task 3.1: Update `refresh_pathways.py` indication processing to use assign_drug_indications()\n - The current code at lines 424-428 uses `dict(zip(...))` which only keeps LAST match per patient  this must be replaced\n - Key changes in the `elif current_chart_type == \"indication\":` block:\n 1. Load drug mapping: `_, st_to_frags = load_drug_indication_mapping()`\n 2. Pass `earliest_hcd_date=df['Intervention Date'].min().strftime('%Y-%m-%d')` to get_patient_indication_groups()\n 3. Call `assign_drug_indications(df, gp_matches_df, st_to_frags)` to get (modified_df, indication_df)\n 4. Use modified_df (not original df) for pathway processing\n 5. indication_df is already in the right format (indexed by modified UPID, 'Directory' column)\n 6. Remove the old match_lookup/dict(zip) code and the manual indication_df building\n - Import assign_drug_indications and load_drug_indication_mapping at top of file\n - This replaces ~50 lines of the old approach with ~10 lines using the new function\n - Can verify with py_compile; full Snowflake test via --dry-run\n### Blocked items:\n- None","originalFile":"# Progress Log - Drug-Aware Indication Matching\n\n## Project Context\n\nThis project extends the indication-based pathway charts (Phase 1-5 complete) with drug-aware matching.\n\n**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.\n\n**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.\n\n## Key Data/Patterns\n\n### DimSearchTerm.csv\n- Located at `data/DimSearchTerm.csv`\n- Columns: Search_Term, CleanedDrugName (pipe-separated), PrimaryDirectorate\n- ~165 rows mapping clinical conditions to drug name fragments\n- Drug fragments are substrings that match standardized drug names from HCD data\n- Some entries have generic fragments: INHALED, CONTINUOUS, STANDARD-DOSE, PEGYLATED\n\n### Current get_patient_indication_groups() in diagnosis_lookup.py\n- Uses CLUSTER_MAPPING_SQL as CTE in Snowflake query\n- Returns ONLY the most recent match per patient (QUALIFY ROW_NUMBER() = 1)\n- Needs to return ALL matching Search_Terms per patient (remove QUALIFY)\n- Batches 500 patients per query\n\n### Modified UPID approach\n- Current: UPID = Provider Code[:3] + PersonKey (e.g., \"RMV12345\")\n- New: UPID = original + \"|\" + search_term (e.g., \"RMV12345|rheumatoid arthritis\")\n- The pipe delimiter \"|\" is safe because existing UPIDs are alphanumeric\n- generate_icicle_chart_indication() treats UPID as an opaque identifier  modified UPIDs work transparently\n- The \" - \" delimiter in pathway ids is used for hierarchy levels, not within UPIDs\n\n### PseudoNHSNoLinked mapping\n- HCD data has PseudoNHSNoLinked column that matches PatientPseudonym in GP records\n- PersonKey is provider-specific local ID  do NOT use for GP matching\n- One PseudoNHSNoLinked can map to multiple UPIDs (multi-provider patients)\n- GP match lookup: PseudoNHSNoLinked  list of matched Search_Terms\n\n### Drug matching logic\n- For each HCD row (UPID + Drug Name):\n 1. Get patient's GP-matched Search_Terms with code_frequency (via PseudoNHSNoLinked)\n 2. Get which Search_Terms list this drug (from DimSearchTerm.csv)\n 3. Intersection = valid indications\n 4. If 1: use it. If multiple: pick highest code_frequency (most GP coding = most likely indication). If 0: fallback to directory.\n- Modified UPID groups drugs under same indication together naturally\n- code_frequency = COUNT(*) of matching SNOMED codes per Search_Term per patient in GP records\n- GP code time range: only count codes from MIN(Intervention Date) onwards (the HCD data window)\n - Reduces noise from old/irrelevant diagnoses, makes frequency more meaningful\n - Pass earliest_hcd_date as parameter to get_patient_indication_groups()\n- Tiebreaker rationale: 47 RA codes vs 2 crohn's codes  RA is clearly the active condition\n\n### Known edge cases\n- Some DimSearchTerm drug fragments are generic (INHALED, ORAL, CONTINUOUS)\n - These could match broadly but are constrained by GP diagnosis requirement\n- A patient visiting multiple providers has multiple UPIDs\n - Each UPID gets its own drug-indication matching independently\n- Same Search_Term appears twice in DimSearchTerm.csv with different directorates\n - e.g., \"diabetes\"  DIABETIC MEDICINE and OPHTHALMOLOGY\n - For indication charts, we use Search_Term not directorate, so this is fine\n\n## Iteration Log\n\n## Iteration 1  2026-02-05\n### Task: 1.3  Build drug-to-Search_Term lookup from DimSearchTerm.csv\n### Why this task:\n- First iteration, chose Phase 1 foundations. Task 1.2 (CSV loading) is self-contained and testable locally without Snowflake.\n- Task 1.1 (Snowflake query update) can't be verified without a live connection  better to do 1.2 first.\n- Both 1.1 and 1.2 are independent, so order doesn't matter for dependencies.\n### Status: COMPLETE\n### What was done:\n- Added `load_drug_indication_mapping()` to `diagnosis_lookup.py`:\n - Loads `data/DimSearchTerm.csv`, builds two dicts:\n - `fragment_to_search_terms`: drug fragment (UPPER)  list of Search_Terms\n - `search_term_to_fragments`: search_term  list of drug fragments (UPPER)\n - Handles duplicate Search_Terms (e.g., \"diabetes\" rows combined)\n - Result: 164 Search_Terms, 346 drug fragments\n- Added `get_search_terms_for_drug()` to `diagnosis_lookup.py`:\n - Returns all Search_Terms whose drug fragments are substrings of the drug name (case-insensitive)\n - Named differently from plan's `drug_matches_search_term()`  returns all matches at once rather than single boolean, more practical for Phase 2\n- Updated `__all__` exports\n### Validation results:\n- Tier 1 (Code): py_compile passed, import check passed\n- Tier 2 (Data): ADALIMUMAB  7 indications (including axial spondyloarthritis, rheumatoid arthritis), OMALIZUMAB  4 indications (asthma, allergic asthma, etc.), PEGYLATED LIPOSOMAL DOXORUBICIN  4 matches via substring, \"ADALIMUMAB 40MG\" matches correctly with dosage info, diabetes fragments combined from 2 CSV rows\n- Tier 3 (Functional): N/A (no UI changes)\n### Files changed:\n- data_processing/diagnosis_lookup.py (added load_drug_indication_mapping, get_search_terms_for_drug)\n- IMPLEMENTATION_PLAN.md (marked 1.2 subtasks [x])\n### Committed: 0779df7 \"feat: add drug-to-indication mapping from DimSearchTerm.csv (Task 1.3)\"\n### Patterns discovered:\n- DimSearchTerm.csv has 164 unique Search_Terms (not 165 as noted) because diabetes appears twice with different directorates but same Search_Term\n- Some drug fragments are very generic: INHALED, CONTINUOUS, ORAL, STANDARD-DOSE, INTRAVENOUS, PEGYLATED, ROUTINE, INDUCTION  these will match broadly but are constrained by the GP diagnosis requirement in Phase 2\n- Function signatures for Phase 2: `get_search_terms_for_drug(drug_name, search_term_to_fragments)` returns list[str]  use this to get candidate indications per drug\n### Next iteration should:\n- Work on Task 1.2: Merge asthma Search_Terms in CLUSTER_MAPPING_SQL and load_drug_indication_mapping()\n - Merge \"allergic asthma\", \"asthma\", \"severe persistent allergic asthma\"  \"asthma\"\n - Keep \"urticaria\" separate\n - This is self-contained and testable locally\n- OR work on Task 1.1: Update `get_patient_indication_groups()` to return ALL matches with code_frequency\n - The current query at line ~1352 of diagnosis_lookup.py uses `QUALIFY ROW_NUMBER() OVER (PARTITION BY pc.\"PatientPseudonym\" ORDER BY pc.\"EventDateTime\" DESC) = 1`  this must be replaced with GROUP BY + COUNT(*)\n - Add `earliest_hcd_date` parameter to restrict GP codes to HCD data window\n - Return columns: PatientPseudonym, Search_Term, code_frequency (not EventDateTime)\n- OR if Snowflake isn't available to test 1.1, skip to Task 2.1 (assign_drug_indications function) which can be built and tested with mock data\n### Blocked items:\n- None\n\n## Iteration 2  2026-02-05\n### Task: 1.2  Merge related asthma Search_Terms in CLUSTER_MAPPING_SQL\n### Why this task:\n- Previous iteration recommended this as the next task (self-contained, testable locally)\n- Both CLUSTER_MAPPING_SQL and load_drug_indication_mapping() need consistent Search_Term names\n- Must be done before Task 1.1 (Snowflake query) to ensure GP lookups return \"asthma\" not \"allergic asthma\"\n### Status: COMPLETE\n### What was done:\n- Updated CLUSTER_MAPPING_SQL: changed 'allergic asthma'  'asthma' (AST_COD) and 'severe persistent allergic asthma'  'asthma' (SEVAST_COD)\n - Now 3 rows for 'asthma': AST_COD, eFI2_Asthma, SEVAST_COD\n - urticaria (XSAL_COD) stays separate\n- Added SEARCH_TERM_MERGE_MAP constant: {\"allergic asthma\": \"asthma\", \"severe persistent allergic asthma\": \"asthma\"}\n- Updated load_drug_indication_mapping() to apply SEARCH_TERM_MERGE_MAP when loading CSV\n - Normalizes Search_Term before accumulating fragments\n - Drug fragments from all 3 original rows combined under \"asthma\" key\n- Exported SEARCH_TERM_MERGE_MAP in __all__\n### Validation results:\n- Tier 1 (Code): py_compile passed, import check passed\n- Tier 2 (Data):\n - \"asthma\" fragments: OMALIZUMAB, BENRALIZUMAB, DUPILUMAB, INHALED, MEPOLIZUMAB, RESLIZUMAB (complete combined list)\n - \"allergic asthma\" no longer exists as separate key\n - \"severe persistent allergic asthma\" no longer exists as separate key\n - \"urticaria\"  ['OMALIZUMAB']  correctly separate\n - OMALIZUMAB maps to: ['asthma', 'urticaria']  correct\n - Total Search_Terms: 162 (was 164, 3 asthma entries  1)\n - Total fragments: 346 (unchanged)\n- Tier 3 (Functional): N/A (no UI changes)\n### Files changed:\n- data_processing/diagnosis_lookup.py (CLUSTER_MAPPING_SQL, SEARCH_TERM_MERGE_MAP, load_drug_indication_mapping)\n- IMPLEMENTATION_PLAN.md (marked 1.2 subtasks [x])\n### Committed: b0a8a9d \"feat: merge asthma Search_Term variants in CLUSTER_MAPPING_SQL and drug mapping (Task 1.2)\"\n### Patterns discovered:\n- SEARCH_TERM_MERGE_MAP is reusable: any future module that receives Search_Terms from Snowflake can apply the same normalization\n- The merge approach (normalize at load time) is cleaner than post-hoc deduplication\n### Next iteration should:\n- Work on Task 1.1: Update `get_patient_indication_groups()` to return ALL matches with code_frequency\n - The current query at ~line 1467 uses `QUALIFY ROW_NUMBER() OVER (PARTITION BY pc.\"PatientPseudonym\" ORDER BY pc.\"EventDateTime\" DESC) = 1`\n - Replace with GROUP BY + COUNT(*) for code_frequency\n - Add `earliest_hcd_date` parameter to restrict GP codes to HCD data window\n - Return columns: PatientPseudonym, Search_Term, code_frequency\n - Empty DataFrame columns should match new return type\n - This requires Snowflake connectivity to fully test, but code changes can be verified with py_compile and import checks\n- OR work on Task 2.1: Create assign_drug_indications()  can be built and tested with mock data\n - This is independent of Task 1.1 if you mock the gp_matches_df input\n### Blocked items:\n- None\n\n## Iteration 3  2026-02-05\n### Task: 1.1  Update get_patient_indication_groups() to return ALL matches with code_frequency\n### Why this task:\n- Previous iteration recommended this as the next task\n- This is the last remaining Phase 1 dependency  Tasks 2.1/2.2 need the GP matches data in the right format (multiple rows per patient with code_frequency)\n- Task 1.1 changes the query fundamentals; better to do this before building assign_drug_indications() which consumes the output\n### Status: COMPLETE\n### What was done:\n- Modified `get_patient_indication_groups()` in `diagnosis_lookup.py`:\n 1. **Removed** `QUALIFY ROW_NUMBER() OVER (PARTITION BY pc.\"PatientPseudonym\" ORDER BY pc.\"EventDateTime\" DESC) = 1`\n 2. **Replaced** with `GROUP BY pc.\"PatientPseudonym\", aic.Search_Term` + `COUNT(*) AS \"code_frequency\"`\n 3. **Added** `earliest_hcd_date: Optional[str] = None` parameter\n 4. **Added** optional `AND pc.\"EventDateTime\" >= %s` when earliest_hcd_date is provided\n 5. **Updated** return columns from `(PatientPseudonym, Search_Term, EventDateTime)` to `(PatientPseudonym, Search_Term, code_frequency)`\n 6. **Updated** all empty DataFrame returns to use new column names\n 7. **Updated** logging to show multiple-rows-per-patient stats (avg indications per patient)\n 8. **Updated** docstring to describe new behavior and parameters\n- Backward compatible: `earliest_hcd_date` defaults to `None`, existing callers still work\n- Note: caller in `refresh_pathways.py` (line 424-428) does `dict(zip(...))` which will only keep last match per patient with new multi-row format  this will be updated in Task 3.1\n### Validation results:\n- Tier 1 (Code): py_compile PASSED, import check PASSED, function signature verified\n- Tier 2 (Data): Empty DataFrame returns correct columns ['PatientPseudonym', 'Search_Term', 'code_frequency']; live Snowflake test deferred to Phase 3/4\n- Tier 3 (Functional): N/A (no UI changes)\n### Files changed:\n- data_processing/diagnosis_lookup.py (modified get_patient_indication_groups function)\n- IMPLEMENTATION_PLAN.md (marked 1.1 subtasks [x])\n### Committed: c93417f \"feat: return ALL GP matches with code_frequency in get_patient_indication_groups (Task 1.1)\"\n### Patterns discovered:\n- The `earliest_hcd_date` parameter is passed as a string in ISO format (YYYY-MM-DD) via Snowflake %s placeholder  Snowflake handles string-to-timestamp comparison implicitly\n- The GROUP BY approach naturally deduplicates SNOMED codes within the same Search_Term  a patient with the same SNOMED code recorded 5 times gets code_frequency=5 (reflecting clinical activity intensity)\n- params list is built dynamically: `batch_pseudonyms + [earliest_hcd_date]` only when date filter is active\n### Next iteration should:\n- Work on Task 2.1: Create `assign_drug_indications()` function\n - This is now unblocked since 1.1 is complete (return format is known)\n - Input: HCD df, gp_matches_df (PatientPseudonym, Search_Term, code_frequency), drug_mapping from load_drug_indication_mapping()\n - Output: (modified_df with UPID|search_term, indication_df mapping modified_UPID  Search_Term)\n - Can be built and tested with mock data (no Snowflake needed)\n - Key logic: for each UPID+Drug pair, intersect drug's Search_Terms with patient's GP matches, pick highest code_frequency as tiebreaker\n - The function needs PseudoNHSNoLinked to look up GP matches, so the df must have that column\n - Task 2.2 (tiebreaker logic) can be done within 2.1 or as a follow-up\n- The final Phase 1 subtask (1.1 verify with live Snowflake) will be tested during Phase 3/4 integration\n### Blocked items:\n- Task 1.1 final subtask \"Verify: Query returns more rows\" requires live Snowflake  deferred to Phase 3/4\n","structuredPatch":[{"oldStart":193,"oldLines":3,"newStart":193,"newLines":63,"lines":[" - The final Phase 1 subtask (1.1 verify with live Snowflake) will be tested during Phase 3/4 integration"," ### Blocked items:"," - Task 1.1 final subtask \"Verify: Query returns more rows\" requires live Snowflake  deferred to Phase 3/4","+","+## Iteration 4  2026-02-05","+### Task: 2.1 + 2.2  Create assign_drug_indications() with tiebreaker logic","+### Why this task:","+- All Phase 1 dependencies complete (1.1 query returns ALL matches, 1.2 asthma merged, 1.3 drug mapping loaded)","+- Task 2.1 is the core matching function needed before Phase 3 pipeline integration","+- Task 2.2 (tiebreaker) is naturally part of 2.1  implemented together","+- Can be built and tested with mock data (no Snowflake needed)","+### Status: COMPLETE","+### What was done:","+- Added `assign_drug_indications()` to `diagnosis_lookup.py`:","+ - Input: HCD df (with UPID, Drug Name, PseudoNHSNoLinked, Directory), gp_matches_df, search_term_to_fragments","+ - Output: (modified_df with UPID|search_term, indication_df mapping modified_UPID  Search_Term)","+ - Builds GP lookup: PseudoNHSNoLinked  {Search_Term: code_frequency}","+ - Caches drugSearch_Term lookups to avoid recomputing per row","+ - For each (UPID, Drug Name) pair:","+ - Intersects drug's Search_Terms with patient's GP matches","+ - Single match: use it","+ - Multiple matches: highest code_frequency wins, alphabetical tiebreak","+ - No match: fallback to \"{Directory} (no GP dx)\"","+ - Applies modified UPIDs via df.apply() (vectorized lookup from cache)","+ - Builds indication_df with unique modified UPID  Directory column","+ - Comprehensive logging: match rate, tiebreaker count, fallback count, top 5 indications","+- Updated __all__ exports","+### Validation results:","+- Tier 1 (Code): py_compile PASSED, import check PASSED","+- Tier 2 (Data): Mock data tests ALL PASSED:","+ - ADALIMUMAB + GP dx (RA + asthma)  matched to RA (drug mapping intersection)","+ - OMALIZUMAB + GP dx (RA + asthma)  matched to asthma (drug mapping intersection)","+ - ADALIMUMAB + GP dx (RA 3 freq + crohn's 2 freq)  tiebreaker picks RA","+ - ADALIMUMAB + GP dx (psoriatic 5 freq + RA 5 freq)  alphabetical tiebreak picks psoriatic arthritis","+ - Higher frequency (47 RA vs 3 psoriatic)  RA wins","+ - No GP match  fallback to directory","+ - Empty GP DataFrame  all fallback","+ - Different drugs with different indications  different modified UPIDs","+- Tier 3 (Functional): N/A (no UI changes yet)","+### Files changed:","+- data_processing/diagnosis_lookup.py (added assign_drug_indications, updated __all__)","+- IMPLEMENTATION_PLAN.md (marked 2.1 and 2.2 subtasks [x])","+### Committed: 408976e \"feat: add assign_drug_indications() for drug-aware indication matching (Task 2.1 + 2.2)\"","+### Patterns discovered:","+- Function signature takes `search_term_to_fragments` (the second element from load_drug_indication_mapping())  NOT the full tuple. Callers must destructure: `_, st_to_frags = load_drug_indication_mapping()`","+- The function uses df.apply() to set modified UPIDs  for large DataFrames (656K rows), this could be slow. If performance is an issue in Phase 3, could vectorize with merge operations instead. But apply with cached lookup dict should be OK.","+- \"crohn's disease\" is NOT in ADALIMUMAB's DimSearchTerm mapping (ADALIMUMAB maps to: ankylosing spondylitis, axial spondyloarthritis, plaque psoriasis, psoriatic arthritis, rheumatoid arthritis, ulcerative colitis, uveitis). Initial test assumption was wrong.","+- indication_df has 'Directory' column (not 'Search_Term') for compatibility with generate_icicle_chart_indication() which expects indication_df.loc[upid, 'Directory']","+### Next iteration should:","+- Work on Task 3.1: Update `refresh_pathways.py` indication processing to use assign_drug_indications()","+ - The current code at lines 424-428 uses `dict(zip(...))` which only keeps LAST match per patient  this must be replaced","+ - Key changes in the `elif current_chart_type == \"indication\":` block:","+ 1. Load drug mapping: `_, st_to_frags = load_drug_indication_mapping()`","+ 2. Pass `earliest_hcd_date=df['Intervention Date'].min().strftime('%Y-%m-%d')` to get_patient_indication_groups()","+ 3. Call `assign_drug_indications(df, gp_matches_df, st_to_frags)` to get (modified_df, indication_df)","+ 4. Use modified_df (not original df) for pathway processing","+ 5. indication_df is already in the right format (indexed by modified UPID, 'Directory' column)","+ 6. Remove the old match_lookup/dict(zip) code and the manual indication_df building","+ - Import assign_drug_indications and load_drug_indication_mapping at top of file","+ - This replaces ~50 lines of the old approach with ~10 lines using the new function","+ - Can verify with py_compile; full Snowflake test via --dry-run","+### Blocked items:","+- None"]}],"userModified":false,"replaceAll":false}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01B3DXVnM4E8MTH91RoUuwp7","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01X6evKFj564nLekKhj9S8vL","name":"Bash","input":{"command":"cd \"C:\\Users\\charlwoodand\\Ralph local\\Tasks\\UI Redesign\" && git add progress.txt && git commit -m \"$(cat <<'EOF'\ndocs: update progress.txt with Iteration 4 results (Task 2.1 + 2.2)\nEOF\n)\"","description":"Commit progress update"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":1649,"cache_read_input_tokens":131241,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":1649},"output_tokens":19,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"017c05a5-867d-472b-a62f-071f2cdea00f"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01X6evKFj564nLekKhj9S8vL","type":"tool_result","content":"[feature/snomed-indication-mapping d9891c8] docs: update progress.txt with Iteration 4 results (Task 2.1 + 2.2)\n 1 file changed, 60 insertions(+)","is_error":false}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"6afdfe6f-45c7-44b8-9a4c-2c8cb7be603d","tool_use_result":{"stdout":"[feature/snomed-indication-mapping d9891c8] docs: update progress.txt with Iteration 4 results (Task 2.1 + 2.2)\n 1 file changed, 60 insertions(+)\r","stderr":"","interrupted":false,"isImage":false}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_016m8YVnwDcBoowsimt6AdT6","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01HbYqma7HJNWDpKq84KpbjY","name":"TodoWrite","input":{"todos":[{"content":"Read project files (progress.txt, IMPLEMENTATION_PLAN.md, guardrails.md)","status":"completed","activeForm":"Reading project files"},{"content":"Build assign_drug_indications() function (Task 2.1 + 2.2)","status":"completed","activeForm":"Building assign_drug_indications() function"},{"content":"Validate code (py_compile, import check, mock data test)","status":"completed","activeForm":"Validating code"},{"content":"Commit and update progress.txt","status":"completed","activeForm":"Committing and updating progress"}]}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":207,"cache_read_input_tokens":132890,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":207},"output_tokens":25,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"031ab433-30a2-4ebe-a4f8-9533bd62a087"}
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01HbYqma7HJNWDpKq84KpbjY","type":"tool_result","content":"Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable"}]},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"bd370e46-6ce7-4eef-8e58-b8736910a0a1","tool_use_result":{"oldTodos":[{"content":"Read project files (progress.txt, IMPLEMENTATION_PLAN.md, guardrails.md)","status":"completed","activeForm":"Reading project files"},{"content":"Build assign_drug_indications() function (Task 2.1 + 2.2)","status":"completed","activeForm":"Building assign_drug_indications() function"},{"content":"Validate code (py_compile, import check, mock data test)","status":"completed","activeForm":"Validating code"},{"content":"Commit and update progress.txt","status":"in_progress","activeForm":"Committing and updating progress"}],"newTodos":[{"content":"Read project files (progress.txt, IMPLEMENTATION_PLAN.md, guardrails.md)","status":"completed","activeForm":"Reading project files"},{"content":"Build assign_drug_indications() function (Task 2.1 + 2.2)","status":"completed","activeForm":"Building assign_drug_indications() function"},{"content":"Validate code (py_compile, import check, mock data test)","status":"completed","activeForm":"Validating code"},{"content":"Commit and update progress.txt","status":"completed","activeForm":"Committing and updating progress"}]}}
{"type":"assistant","message":{"model":"claude-opus-4-6","id":"msg_01BMc3oBVZdps8nZoF4kE5Hh","type":"message","role":"assistant","content":[{"type":"text","text":"**Iteration 4 complete.** Here's the summary:\n\n**Task 2.1 + 2.2: `assign_drug_indications()` ÔÇö COMPLETE**\n\nAdded the core drug-aware indication matching function to `diagnosis_lookup.py`. For each UPID + Drug Name pair:\n1. Gets patient's GP-matched Search_Terms (via PseudoNHSNoLinked)\n2. Gets which Search_Terms list this drug (from DimSearchTerm.csv mapping)\n3. Intersects to find valid indications\n4. Tiebreaker: highest code_frequency wins, alphabetical if tied\n5. Fallback: `{Directory} (no GP dx)` for unmatched drugs\n6. Modifies UPID: `{UPID}|{search_term}`\n\nAll mock data tests pass. Commits: `408976e` (function) and `d9891c8` (progress).\n\n**Next iteration**: Task 3.1 ÔÇö integrate `assign_drug_indications()` into `refresh_pathways.py`, replacing the old `dict(zip())` approach that only kept one match per patient."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":251,"cache_read_input_tokens":133097,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":251},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","uuid":"afa31710-de59-4917-a73d-530a4e62236d"}
{"type":"result","subtype":"success","is_error":false,"duration_ms":300431,"duration_api_ms":280922,"num_turns":29,"result":"**Iteration 4 complete.** Here's the summary:\n\n**Task 2.1 + 2.2: `assign_drug_indications()` ÔÇö COMPLETE**\n\nAdded the core drug-aware indication matching function to `diagnosis_lookup.py`. For each UPID + Drug Name pair:\n1. Gets patient's GP-matched Search_Terms (via PseudoNHSNoLinked)\n2. Gets which Search_Terms list this drug (from DimSearchTerm.csv mapping)\n3. Intersects to find valid indications\n4. Tiebreaker: highest code_frequency wins, alphabetical if tied\n5. Fallback: `{Directory} (no GP dx)` for unmatched drugs\n6. Modifies UPID: `{UPID}|{search_term}`\n\nAll mock data tests pass. Commits: `408976e` (function) and `d9891c8` (progress).\n\n**Next iteration**: Task 3.1 ÔÇö integrate `assign_drug_indications()` into `refresh_pathways.py`, replacing the old `dict(zip())` approach that only kept one match per patient.","stop_reason":null,"session_id":"d2ce1658-c25d-416e-bc13-2d1b50478cab","total_cost_usd":2.5186082499999993,"usage":{"input_tokens":27,"cache_creation_input_tokens":105963,"cache_read_input_tokens":3048617,"output_tokens":12707,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":105963,"ephemeral_5m_input_tokens":0}},"modelUsage":{"claude-opus-4-6":{"inputTokens":27,"outputTokens":12707,"cacheReadInputTokens":3048617,"cacheCreationInputTokens":105963,"webSearchRequests":0,"costUSD":2.5043872499999997,"contextWindow":200000,"maxOutputTokens":32000},"claude-haiku-4-5-20251001":{"inputTokens":12486,"outputTokens":347,"cacheReadInputTokens":0,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.014221,"contextWindow":200000,"maxOutputTokens":64000}},"permission_denials":[],"uuid":"d425aa52-201b-44db-aef9-f7c335873604"}