Search by

pixiekat / hmfp-search-tool-bundle

pixiekat

A symfony bundle that provides the basic application functionality for the HMFP search tool.

Package info

github.com/pixiekat/hmfp-search-tool-bundle

Type:symfony-bundle

pkg:composer/pixiekat/hmfp-search-tool-bundle

Statistics

Installs: 8

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

dev-main / 0.1.x-dev 2026-12-04 10:36 UTC

This package is auto-updated.

Last update: 2026-12-04 10:36:52 UTC


README

Syncing physician claims

physician_claims.active_claim_for mirrors status: it holds the physician's id while a claim is live (verified or approved) and is NULL otherwise. A UNIQUE index on it is what stops two accounts holding the same physician.

The app keeps the two in step (PhysicianClaim::syncExclusivity()), so editing status by hand in SQL leaves them out of step. That can go wrong in two directions, and each has its own find-and-repair pair below.

Always run the SELECT first, so you know which rows the UPDATE will touch before it touches them.

1. Live claims that lost their slot

Caused by setting status back to verified or approved by hand (for example, un-revoking a claim).

Symptom: the app still treats the claim as live — the voter counts by status — but the UNIQUE index is no longer protecting that physician, so a second account could verify a claim on the same person.

-- Find: live claims with no exclusivity slot.
SELECT id, physician_id, status, active_claim_for
  FROM physician_claims
 WHERE status IN ('verified', 'approved')
   AND active_claim_for IS NULL;

-- Repair: give each one its slot back, exactly as syncExclusivity() would.
UPDATE physician_claims
   SET active_claim_for = physician_id
 WHERE status IN ('verified', 'approved')
   AND active_claim_for IS NULL;

This UPDATE can fail on purpose. If two live claims point at the same physician, MariaDB stops it with a duplicate-key error on active_claim_for. That is the index doing its job, not a broken query: two accounts are claiming the same person. A data steward must revoke one of them before the repair will run. Do not drop the index to get past it.

2. Dead claims still holding a slot

Caused by setting status to pending, rejected or revoked by hand (for example, revoking a claim in SQL instead of from the claims admin screen).

Symptom: the UNIQUE index refuses every future claim on that physician, and the claimant sees "Someone else has just claimed this profile" even though nobody has.

-- Find: non-live claims that still hold the exclusivity slot.
SELECT id, physician_id, status, active_claim_for
  FROM physician_claims
 WHERE status NOT IN ('verified', 'approved')
   AND active_claim_for IS NOT NULL;

-- Repair: release the slot.
UPDATE physician_claims
   SET active_claim_for = NULL
 WHERE status NOT IN ('verified', 'approved')
   AND active_claim_for IS NOT NULL;

If the list of live statuses ever changes, update these queries to match ClaimStatus::grantsEditing().

Importer

hmfp:import:physicians (src/Command/ImportPhysiciansCommand.php) reads the hospital's provider demographics extract and turns it into physicians, departments, facilities, specialties and languages, plus the links between them. The extract's format belongs to the hospital's export team; the importer reads it as it is and reports anything it cannot use.

Running it

# Always dry-run first: parses and reports, writes nothing.
php bin/console hmfp:import:physicians --dry-run

# The real import. --no-debug stops the profiler keeping every INSERT in memory.
php bin/console hmfp:import:physicians --no-debug

# A different file, comma-delimited, first 500 providers only.
php bin/console hmfp:import:physicians /path/to/extract.csv -d ',' --limit=500

With no file argument it imports the sample in docs/sample-provider-demographics.csv.

Option What it does
-d, --delimiter Field delimiter. Defaults to |: the extract is pipe-delimited despite the .csv name.
-b, --batch-size Physicians written per flush (default 500).
-l, --limit Stop after this many providers (not rows). Turns off departure detection.
--skip-departments Leave departments and their links untouched.
--skip-facilities Leave facilities and their links untouched.
--dry-run Do everything except write.
-v Also print the line number of every skipped row or value.

The shape of the extract

  • One row per provider per department. The sample has 21,556 rows but only about 10,933 people. Repeat rows aren't errors; they're where a physician's extra departments and facilities come from.

  • Three different separators in one file:

    • | between fields
    • ; inside department and specialty (Ophthalmology; Surgery is two)
    • , inside languages (Albanian, Italian, Spanish)

    The comma never splits any other column, because facility names contain real commas (Mount Auburn Cambridge, IPA).

  • Columns are found by header name, not position. If upstream reorders the spreadsheet, nothing breaks. If a column is renamed or missing, the import stops before writing anything and lists what it found. Every column looking missing usually means the wrong --delimiter.

  • Export artifacts are cleaned: trailing commas on facility_name (0 to 7 of them), a UTF-8 BOM on the first header cell, and doubled spaces in names.

  • Required per row: cred_id, last_name, degree. Rows missing one are skipped and counted by reason. An empty department is fine; about 4% of providers have none.

How a run works

The file is read twice, on purpose.

  1. Pass 1: scan. Reads every row without writing. It counts rows, collects every distinct department, facility, specialty and language name, and builds each provider's full list of them (keyed by cred_id), merging their repeat rows.
  2. Sync the lookup tables. Creates any department, facility, or specialty / language term that doesn't exist yet, in one go, then reads back their ids. Names are matched case-insensitively, so Cardiology and cardiology are one department.
  3. Pass 2: import physicians. Streams the file again, one provider at a time (repeat rows are skipped, since pass 1 already has their data), and decides insert, update or nothing. Writes happen in batches of --batch-size.
  4. Stamp and report. Every physician seen gets the same lastSeenInImportAt timestamp, then a summary table is printed and the run is written to the audit log.

Doing all the department and facility work up front means pass 2 only ever needs integer ids. Those still work after Doctrine's clear() detaches every entity between batches; a cached Department object would not.

Matching: "have I seen this person before?"

Identity is the cred_id column, a credentialing UUID that physicians stores under a UNIQUE index.

In the extract What happens
cred_id already in physicians Update in place, or leave alone if nothing changed
cred_id not found, but an old row with no cred_id has the same name + degree Adopt that row: it gets the cred_id written in
Neither Insert a new physician

Adoption exists for physicians created before the cred_id column did. Each such row can be adopted once, and rows that already have a cred_id are never matched by name. That's what keeps two providers who share a name (the sample has several) from merging into one record.

Name-plus-degree alone is not used as identity because it fails both ways: a physician who earns an MPH would become two rows, and two different Anne M. Valente MDs would become one.

What an import never does

  • Never deletes a physician. Someone missing from the extract is reported under Departures (a stale lastSeenInImportAt) and left in place. One truncated export would otherwise wipe thousands of rows and their bios. A NULL stamp means "created by hand", not "departed". See PhysicianRepository::countDepartedSince().
  • Never touches fields the extract doesn't own, such as bio. Only legalName, credentials, npi, gender, phone, preferredFullName and the links are overwritten.
  • Never mixes vocabularies. Specialty and language links share physician_terms, so each is diffed only against links in its own vocabulary. Otherwise the specialty sync would delete every language link.
  • Never guesses a department's md_staff_code. New departments get NULL; fill them in through the admin UI.

Reading the summary

  • Created / Updated / Unchanged: a normal re-run of a similar file is mostly unchanged.
  • Adopted: pre-cred_id rows given an identity. Should drop to 0 after the first run.
  • Duplicate rows (same cred_id): the repeat rows described above. Expected and large.
  • Rows skipped / Why rows or values were skipped: grouped by reason. Re-run with -v for line numbers to send back to the export team.
  • Departures: only shown for a full, live run.

Warning sign: a run with a sudden large created count and a matching departures count, on a file that should have been mostly unchanged, means cred_ids were reissued upstream. Every physician was re-inserted and the originals look departed. Suspect the identifier before the importer, and raise it with the export team.

Adding a column from the extract

Only some of the extract's 20 columns are imported (for example suffix, image_url and online_booking_url are not). To add one, it has to be wired through in several places:

  1. COLUMNS: map an internal key to the literal header name.
  2. Pass 2 (importPhysicians()): read it from $record, usually through nullIfBlank(), and call its setter in both the insert branch and the update branch.
  3. loadImportIndex(): add it to the select() and to the $byCredId entry, so the current value is in memory.
  4. The change check ($fieldsChanged): compare the new value against the indexed one. Skipping this means a change to only that column is reported as unchanged and never written.

The same field ends up with three spellings along the way, which is easy to trip over:

┌──────────────────────┬─────────────────────┬──────────────────────────────────────────┐
│        Where         │        Name         │        Why it's spelled that way         │
├──────────────────────┼─────────────────────┼──────────────────────────────────────────┤
│ CSV header / $record │ preferred_full_name │ From the extract, via COLUMNS            │
├──────────────────────┼─────────────────────┼──────────────────────────────────────────┤
│ SQL alias / $row     │ preferredFullName   │ Whatever you write after AS in the       │
│                      │                     │ select() in loadImportIndex()            │
├──────────────────────┼─────────────────────┼──────────────────────────────────────────┤
│ Index / $match       │ preferredFullName   │ Whatever key you choose in the $byCredId │
│                      │                     │ entry in loadImportIndex()               │
└──────────────────────┴─────────────────────┴──────────────────────────────────────────┘

If the key is spelled differently in steps 3 and 4, a debug run stops with Undefined array key. Under --no-debug it's only a warning: $match[...] reads null, the comparison fails on every run, and every physician is reported as updated. So test a new column with a normal dry run first.

PubMed research interests

hmfp:pubmed:research-interests (src/Command/HarvestPubMedInterestsCommand.php) looks up each physician's recent papers on PubMed, finds the topics those papers are mainly about, and suggests the most frequent ones as the physician's research interests. Suggestions are added to what the physician already has, never replacing it, and every one goes into the admin review queue like any other profile edit.

Running it

# Always dry-run first: searches and ranks, writes the terms file, changes no physician.
php bin/console hmfp:pubmed:research-interests --dry-run --limit=20 -v

# The real run, looking 10 years back.
php bin/console hmfp:pubmed:research-interests --years=10

# Just one or two physicians, by id.
php bin/console hmfp:pubmed:research-interests --years=10 -p 1570 -p 5556
Option What it does
--years How far back to look, by publication date (default 5).
--affiliation Text the paper's affiliations must contain (default Beth Israel Deaconess Medical).
--top The most PubMed terms to add per physician (default 10).
--min-count The fewest papers a term must appear on to count (default 2).
--max-articles Skip anyone with more papers than this; it usually means two people share a name (default 300).
-p, --physician Only this physician id. Repeatable.
--offset, --limit Skip the first N physicians (by id) / stop after N. --offset is for resuming.
--output-dir Where to write the terms file (default var/pubmed/).
--dry-run Do everything except change physicians. The terms file is still written.
-v Also print each physician's paper count and ranked terms.

Configuration

All optional, set in .env.local:

Variable Why
NCBI_API_KEY Raises PubMed's limit from 3 to 10 requests a second. A full run drops from about 2 hours to about 40 minutes. Free with an NCBI account.
NCBI_EMAIL A contact address NCBI can use if the tool misbehaves. Use a shared team mailbox, not a personal one. Not sent unless set.
NCBI_TOOL How the tool identifies itself to NCBI. Defaults to hmfp-search-tool.

How a run works

For each physician:

  1. Search. Runs the same search a person would type into PubMed, through NCBI's API (E-utilities), not by scraping the website: "Last, First"[Full Author Name] AND "Beth Israel Deaconess Medical"[Affiliation], limited to the --years window. The full name rather than surname + initial (Quintana Y) cuts down mix-ups between people who share initials.
  2. Fetch. Downloads those papers' records, 200 at a time.
  3. Keep only the major topics. Each paper is tagged with MeSH headings, NLM's controlled vocabulary of medical subjects. Some are flagged as the paper's major topics (shown with a * on the PubMed website). Only those are kept, and the * is always stripped before anything is saved.
  4. Rank. Counts how many papers each topic is a major topic of (once per paper), drops anything on fewer than --min-count papers, and keeps the top --top. Ties are sorted by name, so the same papers always give the same list.
  5. Merge and record. The physician's existing research interests stay first, in their own order, and any new PubMed term is added after them. Names are compared ignoring case and spacing. The result is saved as a normal profile edit, labelled PubMed import · run <runid>.

Physicians are saved in batches of 25. If something goes wrong part-way, earlier batches are kept, the failing batch is undone as a whole, and the error tells you which --offset to resume from.

Review and audit

Every run gets a short random run id (e.g. fcdc1cc2). It ties everything together:

  • The review queue. Each change is a PhysicianEdit labelled with the run id. Like every edit in this app it is live straight away as Unreviewed. Rejecting it returns the physician to their previous research interests.
  • The audit log. Three kinds of entry:
    • physician_edit.published: what changed (written for every edit).
    • pubmed.research_interests.harvested: why. The exact query, date window, PubMed ids (PMIDs) and term counts, so a reviewer can repeat the search and check the evidence.
    • pubmed.research_interests.run: one entry per run, with the settings and totals.
  • The terms file. var/pubmed/terms.<runid>.<YYYYMMDD>.txt lists every unique term the run selected, one per line, sorted. Use it to check the vocabulary as a whole ("why is Mice a research interest?"). var/ is outside the public web root and gitignored, so the file is never served or committed. If a run stops part-way, treat its file as a draft: it may include terms from the batch that was undone.

Re-running

Running it again is safe and creates no duplicates:

  • A physician who already has every suggested term gets no edit and is counted as Already had every term. Nothing is added to the review queue.
  • Terms are matched by name, so an existing term is reused rather than created again.
  • Each run writes its own terms file, named with its own run id.

Two things to know:

  • Terms are only ever added. If newer papers push an old topic out of someone's top 10, it stays on their profile.
  • Removed terms come back. If a reviewer rejects a PubMed edit, or a physician deletes a PubMed term from their profile, the next run suggests it again. Their decision is not remembered yet. (The fix would be to skip terms from rejected or removed PubMed edits; the edit log already holds that history.)

Reading the summary

Row Meaning
Updated (Would update in a dry run) Got new terms. Each one is an edit in the review queue.
Already had every term Nothing new to add. Most of the list on a repeat run.
No papers in window The search found nothing. Most physicians on a first run; see below.
Papers, but no term met the bar They have papers, but no topic appears on --min-count of them.
Skipped: likely name clash More than --max-articles papers. Listed for a person to check.
Skipped: unusable name The name has no separate first and last part.
Failed: PubMed error PubMed returned an error. Listed; re-run that physician with -p.

The first full 10-year run (fcdc1cc2, 2026-12-01) gives a sense of normal numbers: of 10,933 physicians, 606 were updated, 9,112 had no papers in the window, 1,151 had papers but no repeated topic, and two were listed for a person to check.

Dealing with the skipped list:

  • Likely name clash. Look the person up on PubMed. A genuinely prolific researcher really can have hundreds of papers. If the results are all theirs, re-run just them with a higher limit: --years=10 -p <id> --max-articles=600.
  • PubMed error. Usually a temporary fault at NCBI (e.g. HTTP request returned 502). Re-run just that physician with -p <id>. The client retries failed HTTP requests on its own, but PubMed sometimes reports a backend fault inside a successful response, and those are not retried yet.

Known limits

  • Multi-word surnames. legalName is stored as "First Middle Last" with no record of where the surname starts, so "De La Cruz" is searched as just "Cruz". That usually finds nothing rather than the wrong person, and is counted under No papers in window. The real fix is to keep first and last names as separate columns at import.
  • Affiliation is per paper, not per author. PubMed matches the affiliation anywhere on the paper. A same-named co-author from another institution on a BIDMC paper could still match. This is one reason every edit goes through review.
  • Full names start in 2002. PubMed only indexes full author names from 2002 on. That covers any window up to about 24 years.

Harvesting procedures and clinical interests

hmfp:interests:harvest (src/Command/HarvestInterestsCommand.php) is the general-purpose version of the PubMed command. It suggests terms for each physician from a source you choose with --source, and records them the same way: merged with what the physician already has, as reviewable edits, with a full audit trail and a terms file.

--source Writes to Data Status
cms (default) Procedures Medicare + Medicaid claims, keyed by NPI Working
findadoc Clinical interests BIDMC Find a Doctor profiles (an export from the web team) Stub: needs the data
export Clinical interests A column in the hospital provider export Stub: needs the column
claude Clinical interests Claude, rewording evidence we already hold (procedures, research topics) Working

Each source decides which profile field it writes to. Billing codes are procedures, not interests, so a flag can't send claims data into "clinical interests" by mistake.

Running it

# Always dry-run first, with -v to see each physician's ranked list and evidence.
php bin/console hmfp:interests:harvest --dry-run -v --limit=50 \
  -f var/cms/medicare-2023.csv \
  -f var/cms/medicaid-provider-spending.csv.gz

# The real run, counting Medicaid claims from 2022 on.
php bin/console hmfp:interests:harvest --since=2022 \
  -f var/cms/medicare-2023.csv -f var/cms/medicare-2022.csv \
  -f var/cms/medicaid-provider-spending.csv.gz
Option What it does
-s, --source Which source (default cms).
-f, --file Input file. Repeatable. .gz is read directly.
--since Earliest year to count, where the source has dates (Medicaid months).
--top The most terms to add per physician (default 10).
--min-score Drop weaker terms. Each source has its own default: cms 11 patients, claude 1 evidence item.
-p, --offset, --limit, --output-dir, --dry-run, -v As in the PubMed command.

The terms file goes to var/interests/terms.<source>.<runid>.<YYYYMMDD>.txt. Edits are labelled <Source> import · run <runid>. The audit entries are interests.harvested (per physician, with each term's code and evidence) and interests.run (one per run).

The CMS source

Getting the files. Download them into var/cms/ (gitignored, outside the web root):

  • Medicare: "Medicare Physician & Other Practitioners – by Provider and Service" on data.cms.gov. One CSV per year. Pass several years to cover more.
  • Medicaid: "Medicaid Provider Spending" on opendata.hhs.gov (2018–2024). If you only have the Parquet version, convert it to CSV first (DuckDB does this in one line).

You don't have to say which file is which. The source tells from the header row, and if a file is neither, it stops and shows the columns it did find.

How a list is built:

  1. Keep only rows for our physicians' NPIs. For Medicaid that's the servicing NPI. The billing NPI is usually the group practice, which would credit every procedure to HMFP.
  2. Drop codes that say nothing about what a physician does: office visits, wellness visits, routine screening and counselling, labs, vaccines, anesthesia, sedation, blood draws, drugs, supplies. The lists are in src/Services/Interests/HcpcsFilter.php, each with a reason. They're a starting point to tune: dry-run, read the output, add to the lists, and update HcpcsFilterTest to match.
  3. Add up patients per code across all files. Medicare and Medicaid together matter because Medicare barely covers paediatrics and obstetrics.
  4. Name each code from Medicare's descriptions. The Medicaid file has none, so a code seen only in Medicaid is skipped and counted under Codes with no name. Adding another Medicare year usually names it. A name over 255 characters won't fit the database, so it's skipped and counted under Names too long.
  5. Rank by patients and keep the top --top.

Read the score as "how much of their practice", not a head count. Medicaid counts patients per month, so a patient seen in two months counts twice, and Medicare splits office and facility rows. Both datasets also hide low-volume combinations for privacy, so a rare procedure someone does a handful of times won't appear.

Before the terms go public: Medicare's descriptions of CPT codes are AMA copyright, distributed by CMS under licence. Confirm with billing or compliance that the hospital's CPT licence covers showing them in this app.

Procedures aren't on the profile form yet. EditableField::Procedures is active, so the review queue and hmfp:projections:rebuild handle it, and search already matches the Procedure vocabulary. It isn't in PhysicianProfileController::TERM_FIELDS, though, so physicians can't edit it and their profile page doesn't list it. Add it there when that's wanted.

Procedures are searchable but never listed. Searching "cataract" finds physicians by their procedures, but the procedure names don't appear as a search filter or as type-ahead suggestions, because they're billing text and search is open to the public. The switch is PhysicianVocabulary::isPubliclyListed(). Only change it once the CPT licence question above is settled.

The Claude source

--source=claude asks Claude to turn evidence we already have into clinical interests a patient would search for. For example, the procedure "Removal of cataract with insertion of lens" becomes Cataracts.

It's a translator, not a researcher. Claude is never told who a physician is: no name, no NPI, no id. It gets only the terms already on their record: specialty, board certifications, procedures (from --source=cms), conditions, and research topics (from the PubMed command). So run those first; this source can only be as good as the evidence they've added. Physicians with nothing but a specialty are skipped without a call, because a specialty alone would only invite a guess.

The grounding check. For every interest, Claude has to list the exact evidence items it came from. Each citation is checked against what was actually sent:

  • An interest that cites nothing real is dropped and counted, never saved.
  • An interest that just repeats the specialty ("Ophthalmology") is dropped.
  • The score is the number of valid citations, so --min-score=2 means "supported by at least two pieces of evidence".

What the grounding check can't do. It proves the cited evidence is real, not that the conclusion follows from it. Two other rules cover that:

  • Anesthesia is never sent (enforced in code). "Anesthesia for … total knee joint replacement" describes the surgeon's operation, and would list the anesthesiologist under "Knee replacement".
  • A test isn't a diagnosis (a prompt rule). A brain MRI supports "Brain MRI", not "Brain tumors". The prompt also rules out routine steps such as placing catheters. Claude can still slip, so these are what reviewers should look for.

Re-running. The clinical interests already on a profile are sent as "already listed", and Claude is told to return only what's new, not a rewording. They aren't evidence, so it can't justify a new interest with one of its own earlier answers. Exact repeats are also removed in code, but spotting a rewording relies on the prompt, so an occasional near-duplicate can still reach the review queue.

Configuration (.env.local):

Variable What it does
ANTHROPIC_API_KEY Required. Changing the key is all it takes to move from a test account to an institutional one.
CLAUDE_MODEL Optional. Default claude-opus-5-5. claude-haiku-5-5 is far cheaper per token; compare a --limit sample of each before a full run.
CLAUDE_EFFORT Optional: low (default), medium or high. Higher means more thinking tokens per physician.

Cost. A dry run does call Claude, because that's the point of it, but writes nothing. The summary shows tokens used and, for known models, an estimated cost per call, so a --limit=20 --dry-run tells you what a full run would cost before you commit to one.

Stopping and resuming. A bad key, an account out of credit or a model the key can't use stops the run cleanly: the batch in progress is saved, because it was already paid for, and the message gives the --offset to resume from once it's fixed. Any other failure, or a refusal, just skips that physician and is counted in the summary.

How the request is made (ClaudeInterestClient): Anthropic's official PHP SDK (anthropic-ai/sdk), structured output (a JSON schema, so the reply always parses), and server-side refusal fallback (fallbacks: "default"), so a policy refusal is retried on a fallback model rather than lost.

Adding a source

  1. Create a class in src/Services/Interests/ implementing InterestSourceInterface.
  2. Give it #[AsTaggedItem('yourkey')].

That's all. It appears in --source automatically. The interface docblock explains each method, and FindADocSource / ProviderExportSource describe what's needed to finish them.