From 4f8c4246992c8f16c18c4087f451c36f130686e1 Mon Sep 17 00:00:00 2001 From: Luca Soldaini Date: Tue, 17 Nov 2026 08:33:53 -0800 Subject: [PATCH] Fix matcher options and spaCy overlaps, reduce index memory, and add offline tests --- .github/workflows/tests.yml | 16 +++ .gitignore | 3 + MANIFEST.in | 3 +- README.md | 38 ++++--- docs/open-issue-plan.md | 102 +++++++++++++++++ quickumls/core.py | 54 +++++---- quickumls/install.py | 66 ++++++++--- quickumls/server.py | 22 +++- quickumls/spacy_component.py | 86 +++++--------- quickumls/toolbox.py | 10 +- requirements.txt | 1 - setup.py | 1 + tests/fixtures/corpora/stopwords/english | 2 + tests/fixtures/umls/MRCONSO.RRF | 10 ++ tests/fixtures/umls/MRSTY.RRF | 8 ++ tests/prepare_sandbox.py | 73 ++++++++++++ tests/standin.py | 40 +++++++ tests/test_index.py | 136 +++++++++++++++++++++++ 18 files changed, 547 insertions(+), 124 deletions(-) create mode 100644 .github/workflows/tests.yml create mode 100644 docs/open-issue-plan.md create mode 100644 tests/fixtures/corpora/stopwords/english create mode 100644 tests/fixtures/umls/MRCONSO.RRF create mode 100644 tests/fixtures/umls/MRSTY.RRF create mode 100644 tests/prepare_sandbox.py create mode 100644 tests/standin.py create mode 100644 tests/test_index.py diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..04938c1 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,16 @@ +name: Tests +on: [push, pull_request] + +jobs: + test: + strategy: + matrix: + os: [ubuntu-latest, macos-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - run: python -m pip install . + - run: cd "$RUNNER_TEMP" && python -m unittest discover -s "$GITHUB_WORKSPACE/tests" -v diff --git a/.gitignore b/.gitignore index b706461..2657f4c 100644 --- a/.gitignore +++ b/.gitignore @@ -96,3 +96,6 @@ simstring/ # Ignored test file test.py + +# Local test environment, licensed UMLS inputs and generated indexes +/.sandbox/ diff --git a/MANIFEST.in b/MANIFEST.in index 66cabd6..f35803c 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,2 +1,3 @@ include requirements.txt -include README.md \ No newline at end of file +include README.md +include tests/test_index.py tests/standin.py tests/fixtures/umls/*.RRF tests/fixtures/corpora/stopwords/english diff --git a/README.md b/README.md index 8ed022e..2caa952 100644 --- a/README.md +++ b/README.md @@ -8,18 +8,28 @@ For more details on how QuickUMLS works, we remand to our paper. This project should be compatible with Python 3 (Python 2 is [no longer supported](https://pythonclock.org/)) and run on any UNIX system (support for Windows is experimental, please report bugs!). **If you find any bugs, please file an issue on GitHub or email the author at luca@ir.cs.georgetown.edu**. +## Try the test vocabulary + +From this checkout in a Python 3.11 environment, install the package once. You can then query the test vocabulary or run the suite. + +```sh +python -m pip install -e . +python tests/standin.py "amber stone" +python -m unittest discover -s tests -v +``` + +`amber stone` matches the invented concept `C2` with a similarity of 1.0. Both commands use the [editable stand-in data](tests/fixtures/umls) and automatically build a temporary index. They run offline after installation and require no UMLS license or model download. + ## Installation -1. **Obtain a UMLS installation** This tool requires you to have a valid UMLS installation on disk. To install UMLS, you must first obtain a [license](https://uts.nlm.nih.gov/license.html) from the National Library of Medicine; then you should download all UMLS files from [this page](https://www.nlm.nih.gov/research/umls/licensedcontent/umlsknowledgesources.html); finally, you can install UMLS using the [MetamorphoSys](https://www.nlm.nih.gov/pubs/factsheets/umlsmetamorph.html) tool as [explained in this guide](https://www.nlm.nih.gov/research/umls/implementation_resources/metamorphosys/help.html). The installation can be removed once the system has been initialized. -2. **Install QuickUMLS**: You can do so by either running `pip install quickumls` or `python setup.py install`. On macOS, using anaconda is **strongly recommended**†. +1. **Obtain a UMLS release.** Follow the [NLM licensing and access instructions](https://www.nlm.nih.gov/databases/umls.html). To use only SNOMED CT or RxNorm, select that source when preparing the subset in [MetamorphoSys](https://www.nlm.nih.gov/research/umls/implementation_resources/metamorphosys/help.html). +2. **Install QuickUMLS.** For the features described here, use Python 3.11 and run `python -m pip install .` from this checkout. Use `python -m pip install '.[leveldb]'` to open or create a LevelDB index. The published release is available with `python -m pip install quickumls`. 3. **Create a QuickUMLS installation** Initialize the system by running `python -m quickumls.install `, where `` is where the installation files are (in particular, we need `MRCONSO.RRF` and `MRSTY.RRF`) and `` is the directory where the QuickUmls data files should be installed. This process will take between 5 and 30 minutes depending how fast the CPU and the drive where UMLS and QuickUMLS files are stored are (on a system with a Intel i7 6700K CPU and a 7200 RPM hard drive, initialization takes 8.5 minutes). `python -m quickumls.install` supports the following optional arguments: - `-L` / `--lowercase`: if used, all concept terms are folded to lowercase before being processed. This option typically increases recall, but it might reduce precision; - `-U` / `--normalize-unicode`: if used, expressions with non-ASCII characters are converted to the closest combination of ASCII characters. - `-E` / `--language`: Specify the language to consider for UMLS concepts; by default, English is used. For a complete list of languages, please see [this table provided by NLM](https://www.nlm.nih.gov/research/umls/knowledge_sources/metathesaurus/release/abbreviations.html#LAT). - - `-d` / `--database-backend`: Specify which database backend to use for QuickUMLS. The two options are `leveldb` and `unqlite`. The latter supports multi-process reading and has better unicode compatibility, and it used as default for all new 1.4 installations; the former is still used as default when instantiating a QuickUMLS client. More info about differences between the two databases and migration info are available [here](https://github.com/Georgetown-IR-Lab/QuickUMLS/wiki/Migration-QuickUMLS-1.3-to-1.4). - - -**†**: If the installation fails on macOS when using Anaconda, install `leveldb` first by running `conda install -c conda-forge python-leveldb`. + - `-d` / `--database-backend` selects storage for CUIs and semantic types. New indexes use `unqlite` by default. The matcher reads the index's backend flag and assumes `leveldb` for older indexes without a flag. + - `--skip-spacy` builds the index without checking or downloading a spaCy model. Before matching, install your model and the NLTK stopwords corpus. See the [test and sandbox instructions](docs/open-issue-plan.md#running-the-tests). ## APIs @@ -28,13 +38,13 @@ A QuickUMLS object can be instantiated as follows: ```python from quickumls import QuickUMLS -matcher = QuickUMLS(quickumls_fp, overlapping_criteria, threshold, - similarity_name, window, accepted_semtypes) +matcher = QuickUMLS(quickumls_fp) ``` Where: - `quickumls_fp` is the directory where the QuickUMLS data files are installed. +- `spacy_model` accepts an installed spaCy package name or a local pipeline directory. By default, the matcher loads the model for the index language. - `overlapping_criteria` (optional, default: "score") is the criteria used to deal with overlapping concepts; choose "score" if the matching score of the concepts should be consider first, "length" if the longest should be considered first instead. - `threshold` (optional, default: 0.7) is the minimum similarity value between strings. - `similarity_name` (optional, default: "jaccard") is the name of similarity to use. Choose between "dice", "jaccard", "cosine", or "overlap". @@ -59,13 +69,11 @@ QuickUMLS can be used for standalone processing but it can also be use as a comp Adding QuickUMLS as a component in a pipeline can be done as follows: ```python -from quickumls.spacy_component import SpacyQuickUMLS +import spacy +import quickumls.spacy_component # registers the quickumls factory -# common English pipeline nlp = spacy.load('en_core_web_sm') - -quickumls_component = SpacyQuickUMLS(nlp, 'PATH_TO_QUICKUMLS_DATA') -nlp.add_pipe(quickumls_component) +nlp.add_pipe('quickumls', config={'quickumls_fp': 'PATH_TO_QUICKUMLS_DATA'}) doc = nlp('Pt c/o shortness of breath, chest pain, nausea, vomiting, diarrrhea') @@ -76,6 +84,8 @@ for ent in doc.ents: print('Semtypes : {}'.format(ent._.semtypes)) ``` +To keep all alternatives, pass `'options': {'best_match': False}` in the factory config and read `doc._.quickumls`. Each group contains its candidate CUIs, scores, and semantic types. `doc.ents` retains upstream entities and adds the highest-ranked compatible QuickUMLS spans. + ## Server / Client Support Starting with v.1.2, QuickUMLS includes a support for being used in a client-server configuration. That is, you can start one QuickUMLS server, and query it from multiple scripts using a client. @@ -86,7 +96,7 @@ To start the server, run `python -m quickumls.server`: python -m quickumls.server /path/to/quickumls/files {-P QuickUMLS port} {-H QuickUMLS host} {QuickUMLS options} ``` -Host and port are optional; by default, QuickUMLS runs on `localhost:4645`. You can also pass any QuickUMLS option mentioned above to the server. To obtain a list of options for the server, run `python -m quickumls.server -h`. +Host and port default to `localhost:4645`. For example, `--accepted-semtypes T047 T184` restricts the server to concepts with either semantic type. Run `python -m quickumls.server -h` for the available options. To load the client, import `get_quickumls_client` from `quickumls`: diff --git a/docs/open-issue-plan.md b/docs/open-issue-plan.md new file mode 100644 index 0000000..0281515 --- /dev/null +++ b/docs/open-issue-plan.md @@ -0,0 +1,102 @@ +# QuickUMLS fix and test plan + +The November 15 review covered all 30 [open GitHub issues](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues?q=is%3Aissue%20is%3Aopen) against [b8fed22](https://github.com/Georgetown-IR-Lab/QuickUMLS/tree/b8fed224c125b245176ea250b0f056701c156219). The issue tables below retain the acceptance criteria. The November 17 results describe this checkout. + +## Implementation order and checks + +| Order | Work | Evidence or next test | +| --- | --- | --- | +| 1 | Matcher flags (#74, #102), model selection (#69) and server semantic types (#91) | Implemented. Exercise all flag combinations, model paths and CLI filtering. A loopback client and a direct matcher returned the same results against the real index. | +| 2 | spaCy factory, extension registration and overlapping entities (#79, #94, #60) | Implemented. Reuse a pipeline on successive documents, construct a second pipeline, and verify simultaneous CUIs, upstream entities, and score-versus-length ranking on a fuzzy match. | +| 3 | Installer memory (#64, #95) | The new indexer uses one temporary SQLite table for term and CUI deduplication. Record time, peak RSS, and output parity. Repeat under a measured WSL memory limit before resolving #95. The semantic-type map and native SimString writer still consume memory. | +| 4 | Default storage and native installations (#98, #73, #101 and related packaging reports) | UnQLite works without installing LevelDB. An unmarked LevelDB index built with the prior code reopened with the optional binding. The Python 3.12 SimString import and native Windows builds still need upstream work. Add those platforms to CI once a released binding installs and round-trips the fixture. | +| 5 | Remaining platform, performance and terminology requests | Use the small fixture to isolate Windows retrieval (#82), then reproduce external-volume locking (#58). Extend the English NER benchmark (#77) to other supported models before changing the default. For #78, prototype a source-specific ICD lookup and verify zero, one and multiple codes. | + +The published 1.4.2 wheel loaded the English model and produced entities with a directly constructed component on the real index (#65, #68, #81). The wheel and source distribution built from this checkout each passed the synthetic suite outside the source tree. A clean Colab restart, native Windows, and a constrained WSL build still need their own runs. + +For #77, excluding NER from `en_core_web_sm` 3.8.0 improved warm throughput 1.77× on four short texts and 1.62× on two 116-token texts against the small index. Match outputs agreed under all four combinations of flags. To try this with the model override, save a pipeline loaded with `exclude=["ner"]` using spaCy's `to_disk` and pass that directory as `spacy_model`. + +## Running the tests + +In a Python 3.11 environment, install QuickUMLS from the checkout and use the stand-in vocabulary for daily development. + +```sh +python -m pip install -e . +python -m unittest discover -s tests -v +python tests/standin.py "amber stone" +``` + +The [fictional RRF files](../tests/fixtures/umls) supply seven concepts, including overlapping phrases, repeated spellings, accented text and a non-English row. The tests use the real indexer and matcher with a temporary index, a blank English spaCy pipeline, and a two-word stopword list. After package installation, both commands work offline. The example returns `C2` at offsets 0–11. + +### Optional licensed release checks + +For release validation, provision the English model and stopwords, then prepare a subset from a full-release ZIP and enable the licensed source comparison explicitly. + +```sh +python -m spacy download en_core_web_sm +export NLTK_DATA="$PWD/.sandbox/nltk_data" +python -m nltk.downloader -d "$NLTK_DATA" stopwords +python tests/prepare_sandbox.py "$HOME/Downloads/umls-2026AB-metathesaurus-full.zip" +mkdir -p .sandbox/index +python -m quickumls.install --skip-spacy -L -U .sandbox/META .sandbox/index +QUICKUMLS_TEST_LICENSED=1 python -m unittest discover -s tests -v +``` + +The existing 2026AB subset contains 434 atoms across 24 CUIs. To check the probe terms against all English rows in the prepared full index, use `QUICKUMLS_TEST_FULL=1` in place of `QUICKUMLS_TEST_LICENSED=1`. To rebuild that index, extract `*/META/MRCONSO.RRF` and `*/META/MRSTY.RRF` into `.sandbox/full/META` and run the same installer with `.sandbox/full/index` as the destination. + +## Installer measurements + +The comparison used native UnQLite and SimString on Apple Silicon with Python 3.11. For the 1M-row check, both builds processed the same first 1,000,000 MRCONSO rows and corresponding MRSTY rows with English selection and lowercasing. All 165,296 stored terms had the same CUIs, semantic types and preferred flags as the source. All native SimString files matched byte for byte. Timings and peak RSS below are medians of three runs per revision for that sample. + +| MRCONSO input | Original peak RSS / time | This checkout peak RSS / time | +| --- | --- | --- | +| 100,000 rows | 183.92 MiB / 0.780 s | 183.88 MiB / 0.816 s | +| 1,000,000 rows | 327.53 MiB / 4.290 s | 295.77 MiB / 4.701 s | +| Full 2026AB release (18,302,757 rows) | 12.02 GiB / 233.6 s | 9.26 GiB / 263.3 s | + +The full-build row is a single run per revision on the same Mac, with lowercasing, Unicode folding and the model check skipped for both. The indexer processed 10,906,659 English atoms. Peak memory fell 23% and the build took 30 seconds longer. All 1,078 native SimString files matched the original build byte for byte. The licensed test also reopened the new index and verified the probe CUIs, semantic types and preferred flags against the full RRF inputs. + +## Matcher and server + +| Issues | Plan | Ready to close when | +| --- | --- | --- | +| [#74](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/74), [#102](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/102) · Public match flags ignored | In [core.py](../quickumls/core.py), `match()` calls `_match(parsed)` without either argument. Adapt [PR #75](https://github.com/Georgetown-IR-Lab/QuickUMLS/pull/75) to forward both by name and keep the existing defaults. The spaCy component already forwards them. | On the public API, `best_match=False` retains overlapping spans and `ignore_syntax=True` admits a term normally removed by syntax heuristics. Exercise all four flag combinations and the no-argument default. Resolve both reports with the same patch. | +| [#91](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/91) · Server cannot select semantic types | Add `--accepted-semtypes T047 T184` to [server.py](../quickumls/server.py), validate the TUI format, and pass the set to the matcher. When omitted, retain the constructor default; passing `None` would turn off filtering. | A local client and a direct matcher return the same results with defaults and with a custom subset. A malformed ID fails at argument parsing; the option appears in help. | +| [#82](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/82) · Windows returns no matches | The reporter isolated the difference to SimString retrieval on Windows versus Ubuntu. Build the same small index **on each OS** and check writer finalization, exact and fuzzy retrieval, then CUI lookup and semantic filtering. Fix the first layer that differs. | Both platforms retrieve the inserted term after reopening the index, and the public matcher returns its expected CUI. If the fixture already passes, collect the reporter's index flags and binding build before attributing the failure. | + +## Native packages and release verification + +| Issues | Plan | Ready to close when | +| --- | --- | --- | +| [#98](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/98), [#73](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/73), [#101](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/101) · LevelDB blocks Python 3.12 and native Windows installs | New indexes use UnQLite, but [requirements.txt](../requirements.txt) and [toolbox.py](../quickumls/toolbox.py) require LevelDB unconditionally. Make legacy LevelDB an optional dependency loaded only for that backend, including old indexes without a backend flag. Evaluate [PR #99](https://github.com/Georgetown-IR-Lab/QuickUMLS/pull/99) for that path: [Plyvel](https://plyvel.readthedocs.io/en/latest/api.html#plyvel.DB.get) returns a default on a missing key; the current adapter expects `KeyError`. Also update the [SimString loader](https://github.com/Georgetown-IR-Lab/simstring/blob/master/quickumls_simstring/simstring.py), which imports [`imp`, removed in Python 3.12](https://docs.python.org/3/library/imp.html). | Install and query an UnQLite index with no LevelDB on Ubuntu 24.04/Python 3.12 and native Windows. Separately read a pre-change LevelDB index, exercise misses, inserts and duplicates, and check that a missing legacy dependency gives an actionable error. | +| [#76](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/76), [#83](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/83), [#84](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/84), [#51](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/51) · SimString packaging on Windows | The first three traces fail while reading package metadata under GBK or CP1252; pip's resolver message in #83 is downstream. #51 also gets as far as missing MSVC/iconv headers. Compare [SimString's setup](https://github.com/Georgetown-IR-Lab/simstring/blob/master/setup.py) with its [published source distribution](https://pypi.org/project/quickumls-simstring/). Package the UTF-8 read and working iconv discovery, build native wheels, and update QuickUMLS's dependency floor only after those artifacts are available. Replace the README's legacy `setup.py install` path with `python -m pip install .`. | On native Windows, build metadata under both locales with UTF-8 mode off; test a source build with the documented compiler and iconv paths. A fresh wheel install must import the binding and round-trip a Unicode term without a compiler or local source edits. | +| [#62](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/62) · Linux extension cannot resolve `libiconv` | The error occurs on importing `_simstring.so`, before either RRF file is opened. Inspect linkage in clean Conda and system-Python environments; fix the binding's build or packaged runtime library in the environment that fails. | A fresh Linux process imports the release artifact and writes/reads a Unicode term without `LD_PRELOAD`. Document the affected build and interpreter so notebook users can select the repaired environment. | +| [#63](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/63) · SimString has no `writer` | The report used 1.3's top-level `simstring` and was resolved locally by installing the binding. Verify the current packaged import, `from quickumls_simstring import simstring`, and document the distinction from unrelated packages of the same name. | In a clean Linux/WSL environment both reader and writer work through the installed package. If not, capture the imported module path and fix the artifact at fault. | +| [#70](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/70) · macOS UnQLite build | The reporter confirmed an isolated Conda environment returned CUIs on an Intel Mac after the system-Python build failed. Document a verified macOS installation path and distinguish Intel from Apple Silicon when listing support. | A clean environment on an advertised architecture installs and matches the fixture. Record the working versions and close the original report with its confirmed workaround. | +| [#65](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/65), [#81](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/81) · PyPI package missing component or constructor flag | Both reports predate [release 1.4.2](https://pypi.org/project/quickumls/1.4.2/#files). Inspection of its published wheel confirmed that it ships both the component module and the constructor flag. Test the wheel and source distribution outside the checkout, then add that check to future releases. | Each artifact can import and construct `SpacyQuickUMLS` with the fixture without a constructor error or a second model load. Record the working version; cut another release only if the published artifacts fail this check and need a change. | + +## spaCy integration and performance + +| Issues | Plan | Ready to close when | +| --- | --- | --- | +| [#79](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/79), [#94](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/94) · Pipeline setup and duplicate extensions | Register a spaCy 3 factory in [spacy_component.py](../quickumls/spacy_component.py) and change the README to `nlp.add_pipe("quickumls", config={...})`. Construct the matcher once per pipeline. Make registration of `Span` extensions idempotent and handle a conflicting third-party extension without overwriting it. | Run the example verbatim on two documents and build a second pipeline in the same process without E966 or E090. A pre-existing incompatible extension is preserved and the conflict is reported clearly. | +| [#60](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/60) · Overlapping entities crash | Reconcile [PR #61](https://github.com/Georgetown-IR-Lab/QuickUMLS/pull/61) and [PR #88](https://github.com/Georgetown-IR-Lab/QuickUMLS/pull/88). Preserve candidate CUIs, scores and semantic types in a QuickUMLS-specific collection, including separate metadata for CUIs at identical offsets. Add only deterministic non-overlapping winners to `doc.ents`, honoring the configured score/length policy and preserving existing entities. | Two CUIs for one span, nested spans, and an overlap with an upstream NER entity all return usable candidates without an exception or lost metadata. Test both ranking policies. | +| [#68](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/68), [#86](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/86) · Obsolete model name and TLS download failure | The English mapping from [PR #72](https://github.com/Georgetown-IR-Lab/QuickUMLS/pull/72) is present in the [1.4.2 wheel](https://pypi.org/project/quickumls/1.4.2/#files). Verify at runtime that it loads a preinstalled `en_core_web_sm`. For restricted networks, document preinstalling the model and NLTK stopwords; offer an offline path that names missing assets without downloading. Keep certificate verification enabled. | With both resources present and networking disabled, build and query the index. With the model absent, the offline error names the full model and how to supply it. Treat any remaining certificate failure separately from the old `en` shortcut. | +| [#69](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/69) · Custom model | Add an optional standalone model name or path that overrides the language mapping. Keep the existing default; the pipeline component should reuse its caller's pipeline. Use the selected name/path in load errors. | The default model and a custom installed model both produce results; a missing override identifies the correct model. Component mode does not load an extra pipeline. | +| [#77](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/77) · Faster short-text matching | Benchmark standalone matching with NER excluded; it does not consume NER entities. After the flag fix, also compare tokenizer-only processing for `ignore_syntax=True`. Keep syntax annotations in the default path and leave caller-owned pipelines untouched. | Record warm throughput on short and long inputs with model/version specified. Adopt only changes that improve measured performance while preserving CUIs, offsets and scores; the reported 2× is a hypothesis. | + +## Index construction + +| Issues | Plan | Ready to close when | +| --- | --- | --- | +| [#64](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/64), [#95](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/95) · Memory usage and interrupted builds | [install.py](../quickumls/install.py) retains the semantic-type map, all seen CUI/term pairs, and all unique SimString terms. Profile each phase; use disk-backed membership for exact deduplication and move semantic types to disk if needed. Isolate the memory work in [PR #67](https://github.com/Georgetown-IR-Lab/QuickUMLS/pull/67) from its preferred-term API change, and check its duplicate-insertion tradeoff. #95's WSL process was killed near 5.5M rows; check exit status, WSL memory limit, OOM logs and disk space before declaring it the same defect. | Compare peak RSS, time, disk usage and query output on increasing synthetic inputs. Finish a full licensed build under a recorded memory limit; preserve duplicate handling, shared CUIs and preferred flags. Close #95 against this fix only if its failure is reproduced or confirmed. | +| [#58](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/58) · UnQLite lock on external macOS volume | Identify the filesystem and whether another process holds a lock. Compare a single writer on internal and external volumes with intentional writer contention. Explicitly close database handles on success and failure; report the locked path and document building locally and copying the closed index if needed. | A completed index can be reopened after moving it; a competing writer fails clearly and retry succeeds after release. Do not classify the external-volume failure as a deadlock without reproducing it. | + +## Setup guidance and terminology requests + +| Issues | Plan | Ready to close when | +| --- | --- | --- | +| [#90](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/90) · Broken license link | Replace the obsolete README URL with [NLM's licensing and access instructions](https://www.nlm.nih.gov/databases/umls.html). | From the README, a new user can reach the UTS account and license-request steps. | +| [#92](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/92) · Missing index on Colab | Show three distinct locations in a notebook example: the installed Python package, the user's licensed RRF input, and a persistent generated index. Run the installer on the input, then point the matcher at its **output**, not `site-packages`. Improve the missing-index error to name the required directory and command. | A fresh runtime builds a small index, and another runtime reopens the saved index and returns the known CUI without rebuilding. | +| [#89](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/89) · Only SNOMED or RxNorm | Turn the maintainer's answer into a README recipe: select the desired sources when creating the [MetamorphoSys subset](https://www.nlm.nih.gov/research/umls/implementation_resources/metamorphosys/help.html), then index its RRF output. Explain that source filtering and semantic-type filtering are different. | In a subset, verify the `MRCONSO.SAB` source inventory, match a retained term and exclude a source-only term from the omitted vocabulary. No matcher change is needed. | +| [#78](https://github.com/Georgetown-IR-Lab/QuickUMLS/issues/78) · CUI to ICD code | Document a lookup over the user's release of [MRCONSO](https://www.ncbi.nlm.nih.gov/books/NBK9685/table/ch03.T.concept_names_and_sources_file_mr/): filter by matched CUI and requested `SAB`, then return distinct `CODE` values. Distinguish ICD10 from ICD10CM and specify handling of suppressed rows. Offer an optional indexed lookup if in-process results are wanted. | An example reports zero, one, or multiple codes for the requested source without inferring a code where none exists. Existing indexes and default match output stay compatible. | diff --git a/quickumls/core.py b/quickumls/core.py index 7164d18..589a337 100644 --- a/quickumls/core.py +++ b/quickumls/core.py @@ -27,7 +27,7 @@ def __init__( similarity_name='jaccard', min_match_length=3, accepted_semtypes=constants.ACCEPTED_SEMTYPES, verbose=False, keep_uppercase=False, - spacy_component = False): + spacy_component=False, spacy_model=None): """Instantiate QuickUMLS object This is the main interface through which text can be processed. @@ -53,6 +53,10 @@ def __init__( distinguishing acronyms from normal words. For this the database should be installed without the -L option. Defaults to False. + spacy_model (str or Path, optional): Installed spaCy package name or + pipeline directory for standalone matching. Defaults to the + model for the index language. Component mode uses the + caller's pipeline. Raises: ValueError: Raises a ValueError if QuickUMLS was installed for a language that is not currently supported TODO: verify this? @@ -74,7 +78,8 @@ def __init__( valid_similarities = {'dice', 'jaccard', 'cosine', 'overlap'} err_msg = ('"{}" is not a valid similarity name. Choose between ' '{}'.format(similarity_name, ', '.join(valid_similarities))) - assert not(valid_similarities in valid_similarities), err_msg + if similarity_name not in valid_similarities: + raise ValueError(err_msg) self.similarity_name = similarity_name simstring_fp = os.path.join(quickumls_fp, 'umls-simstring.db') @@ -120,12 +125,10 @@ def __init__( raise ValueError('Language "{}" not supported'.format(self.language_flag)) elif constants.LANGUAGES[self.language_flag] is None: self._stopwords = set() - spacy_lang = 'XXX' else: self._stopwords = set( nltk.corpus.stopwords.words(constants.LANGUAGES[self.language_flag]) ) - spacy_lang = constants.SPACY_LANGUAGE_MAP[self.language_flag] database_backend_fp = os.path.join(quickumls_fp, 'database_backend.flag') if os.path.exists(database_backend_fp): @@ -152,18 +155,18 @@ def __init__( # In this case, the pipeline is external to this current class self.nlp = None else: - try: - self.nlp = spacy.load(spacy_lang) - except OSError: - msg = ( - 'Model for language "{}" is not downloaded. Please ' - 'run "python -m spacy download {}" before launching ' - 'QuickUMLS' - ).format( - self.language_flag, - constants.SPACY_LANGUAGE_MAP.get(self.language_flag, 'xx') + model = spacy_model if spacy_model is not None else constants.SPACY_LANGUAGE_MAP.get(self.language_flag) + if model is None: + raise ValueError( + 'No default spaCy model for language "{}". Supply an ' + 'installed model name or path with spacy_model.'.format(self.language_flag) ) - raise OSError(msg) + try: + self.nlp = spacy.load(model) + except OSError as exc: + hint = ('Run "python -m spacy download {}".'.format(model) + if spacy_model is None else 'Check the package name or pipeline directory.') + raise OSError('Could not load spaCy model "{}". {}'.format(model, hint)) from exc self.ss_db = toolbox.SimstringDBReader( simstring_fp, similarity_name, threshold @@ -270,21 +273,12 @@ def _make_ngrams(self, sent): span_end = min(sent_length, i + self.window) + 1 - # we take a shortcut if the token is the last one - # in the sentence - if ( - i + 1 == sent_length and # it's the last token - self._is_valid_end_token(tok) and # it's a valid end token - len(tok) >= self.min_match_length # it's of miminum length - ): - yield(tok.idx, tok.idx + len(tok), tok.text) - for j in xrange(i + 1, span_end): if compensate: compensate = False continue - if sent[j - 1] in invalid_mid_tokens: + if sent[j - 1].i in invalid_mid_tokens: break if not self._is_valid_end_token(sent[j - 1]): @@ -382,7 +376,7 @@ def _select_score(match): def _select_longest(match): return ((match[0]['end'] - match[0]['start']), match[0]['similarity']) - def _select_terms(self, matches): + def _select_terms(self, matches, occupied=()): sort_func = ( self._select_longest if self.overlapping_criteria == 'length' else self._select_score @@ -391,6 +385,8 @@ def _select_terms(self, matches): matches = sorted(matches, key=sort_func, reverse=True) intervals = toolbox.Intervals() + for interval in occupied: + intervals.append(interval) final_matches_subset = [] for match in matches: @@ -434,8 +430,8 @@ def match(self, text, best_match=True, ignore_syntax=False): Args: text (str): Text on which to run the algorithm - best_match (bool, optional): Whether to return only the top match or all overlapping candidates. Defaults to True. - ignore_syntax (bool, optional): Wether to use the heuristcs introduced in the paper (Soldaini and Goharian, 2016). TODO: clarify,. Defaults to False. + best_match (bool, optional): Select non-overlapping spans when true. + ignore_syntax (bool, optional): Skip the syntactic heuristics when true. Returns: List: List of all matches in the text @@ -445,7 +441,7 @@ def match(self, text, best_match=True, ignore_syntax=False): parsed = self.nlp(u'{}'.format(text)) # pass in parsed spacy doc to get concept matches - matches = self._match(parsed) + matches = self._match(parsed, best_match=best_match, ignore_syntax=ignore_syntax) return matches diff --git a/quickumls/install.py b/quickumls/install.py index 0c1998c..873ca09 100644 --- a/quickumls/install.py +++ b/quickumls/install.py @@ -3,10 +3,13 @@ # built in modules import argparse import codecs +from contextlib import closing, contextmanager import os from six.moves import input import shutil +import sqlite3 import sys +from tempfile import TemporaryDirectory import time try: from unidecode import unidecode @@ -48,7 +51,16 @@ def get_mrconso_iterator(path, headers, lang='ENG'): def extract_from_mrconso( mrconso_path, mrsty_path, opts, mrconso_header=HEADERS_MRCONSO, mrsty_header=HEADERS_MRSTY): + atoms = _iter_atoms(mrconso_path, mrsty_path, opts, mrconso_header, mrsty_header) + with _seen_database(getattr(opts, 'destination_path', None)) as seen: + for atom in atoms: + term, cui = atom[:2] + if _first_pair(seen, term, cui): + yield atom + +def _iter_atoms(mrconso_path, mrsty_path, opts, + mrconso_header=HEADERS_MRCONSO, mrsty_header=HEADERS_MRSTY): start = time.time() print('loading semantic types...', end=' ') sys.stdout.flush() @@ -63,7 +75,6 @@ def extract_from_mrconso( total = countlines(mrconso_path) - processed = set() i = 0 for content in mrconso_iterator: @@ -87,11 +98,6 @@ def extract_from_mrconso( if opts.normalize_unicode: concept_text = unidecode(concept_text) - if (cui, concept_text) in processed: - continue - else: - processed.add((cui, concept_text)) - yield (concept_text, cui, sem_types[cui], preferred) delta = time.time() - start @@ -102,7 +108,25 @@ def extract_from_mrconso( print(status) -def parse_and_encode_ngrams(extracted_it, simstring_dir, cuisty_dir, database_backend): +@contextmanager +def _seen_database(directory): + # Track original spellings. The permanent databases normalize their keys to + # NFKD, which can merge distinct input terms with different preferred flags. + with TemporaryDirectory(dir=directory) as temp: + with closing(sqlite3.connect(os.path.join(temp, 'seen.sqlite'))) as db: + # These keys can be discarded on any failure, including an interruption. + db.execute('PRAGMA journal_mode = OFF') + db.execute('CREATE TABLE seen (term TEXT, cui TEXT, ' + 'PRIMARY KEY (term, cui)) WITHOUT ROWID') + yield db + + +def _first_pair(db, term, cui): + return db.execute('INSERT OR IGNORE INTO seen VALUES (?, ?)', (term, cui)).rowcount == 1 + + +def parse_and_encode_ngrams(extracted_it, simstring_dir, cuisty_dir, database_backend, + deduplicate_pairs=False): # Create destination directories for the two databases mkdir(simstring_dir) mkdir(cuisty_dir) @@ -110,14 +134,17 @@ def parse_and_encode_ngrams(extracted_it, simstring_dir, cuisty_dir, database_ba ss_db = SimstringDBWriter(simstring_dir) cuisty_db = CuiSemTypesDB(cuisty_dir, database_backend=database_backend) - simstring_terms = set() - - for i, (term, cui, stys, preferred) in enumerate(extracted_it, start=1): - if term not in simstring_terms: - ss_db.insert(term) - simstring_terms.add(term) - - cuisty_db.insert(term, cui, stys, preferred) + with _seen_database(cuisty_dir) as seen: + for term, cui, stys, preferred in extracted_it: + first_pair = _first_pair(seen, term, cui) + if first_pair: + # The (term, cui) primary key also indexes the term by itself. + other = seen.execute('SELECT 1 FROM seen WHERE term = ? LIMIT 1 OFFSET 1', + (term,)).fetchone() + if other is None: + ss_db.insert(term) + if first_pair or not deduplicate_pairs: + cuisty_db.insert(term, cui, stys, preferred) def install_spacy(lang): @@ -161,6 +188,8 @@ def parse_args(): '-E', '--language', default='ENG', choices=LANGUAGES, help='Extract concepts of the specified language' ) + ap.add_argument('--skip-spacy', action='store_true', + help='Build the index without loading or downloading a spaCy model') opts = ap.parse_args() return opts @@ -168,7 +197,8 @@ def parse_args(): def main(): opts = parse_args() - install_spacy(opts.language) + if not opts.skip_spacy: + install_spacy(opts.language) if not os.path.exists(opts.destination_path): msg = ('Directory "{}" does not exists; should I create it? [y/N] ' @@ -220,13 +250,13 @@ def main(): mrconso_path = os.path.join(opts.umls_installation_path, 'MRCONSO.RRF') mrsty_path = os.path.join(opts.umls_installation_path, 'MRSTY.RRF') - mrconso_iterator = extract_from_mrconso(mrconso_path, mrsty_path, opts) + mrconso_iterator = _iter_atoms(mrconso_path, mrsty_path, opts) simstring_dir = os.path.join(opts.destination_path, 'umls-simstring.db') cuisty_dir = os.path.join(opts.destination_path, 'cui-semtypes.db') parse_and_encode_ngrams(mrconso_iterator, simstring_dir, cuisty_dir, - database_backend=opts.database_backend) + database_backend=opts.database_backend, deduplicate_pairs=True) if __name__ == '__main__': diff --git a/quickumls/server.py b/quickumls/server.py index cc32c2c..6127dd2 100644 --- a/quickumls/server.py +++ b/quickumls/server.py @@ -1,5 +1,7 @@ -from argparse import ArgumentParser +import re +from argparse import ArgumentParser, ArgumentTypeError +from . import constants from .core import QuickUMLS from .network import run_server @@ -13,13 +15,20 @@ def run_quickumls_server(opts): window=opts.window, min_match_length=opts.min_match_length, verbose=opts.verbose, - keep_uppercase=opts.keep_uppercase + keep_uppercase=opts.keep_uppercase, + accepted_semtypes=set(opts.accepted_semtypes) ) run_server(matcher, host=opts.host, port=opts.port, buffersize=4096) -def parse_args(): +def semantic_type(value): + if not re.fullmatch(r'T[0-9]{3}', value): + raise ArgumentTypeError('expected a semantic type like T047, got {!r}'.format(value)) + return value + + +def parse_args(argv=None): ap = ArgumentParser( prog='QuickUMLS server', description=( @@ -68,6 +77,11 @@ def parse_args(): '-l', '--min-match-length', default=3, type=int, help='minimum length of a match' ) + ap.add_argument( + '--accepted-semtypes', '--accepted_semtypes', metavar='TUI', nargs='+', + type=semantic_type, default=constants.ACCEPTED_SEMTYPES, + help='accept concepts with any of these semantic types, e.g. T047 T184' + ) ap.add_argument( '-v', '--verbose', action='store_true', help='return verbose information while running' @@ -79,7 +93,7 @@ def parse_args(): 'useful for distinguishing acronyms from normal words. For this ' 'the database should be installed without the -L option.' ) - return ap.parse_args() + return ap.parse_args(argv) def main(): diff --git a/quickumls/spacy_component.py b/quickumls/spacy_component.py index f64982f..94ea6cd 100644 --- a/quickumls/spacy_component.py +++ b/quickumls/spacy_component.py @@ -1,67 +1,41 @@ -import spacy -from spacy.tokens import Span -from spacy.strings import StringStore +from spacy.language import Language +from spacy.tokens import Doc, Span from .core import QuickUMLS -from . import constants + + +@Language.factory("quickumls", default_config={"options": {}}) +def create_quickumls(nlp, name, quickumls_fp, options): + return SpacyQuickUMLS(nlp, quickumls_fp, **options) + class SpacyQuickUMLS(object): + """Add UMLS entities to a pipeline and expose candidate groups on doc._.quickumls.""" name = 'QuickUMLS matcher' - - def __init__(self, nlp, quickumls_fp, best_match=True, ignore_syntax=False, **kwargs): - """Instantiate SpacyQuickUMLS object - - This creates a QuickUMLS spaCy component which can be used in modular pipelines. - This module adds entity Spans to the document where the entity label is the UMLS CUI and the Span's "underscore" object is extended to contains "similarity" and "semtypes" for matched concepts. - Args: - nlp: Existing spaCy pipeline. This is needed to update the vocabulary with UMLS CUI values - quickumls_fp (str): Path to QuickUMLS data - best_match (bool, optional): Whether to return only the top match or all overlapping candidates. Defaults to True. - ignore_syntax (bool, optional): Wether to use the heuristcs introduced in the paper (Soldaini and Goharian, 2016). TODO: clarify,. Defaults to False - **kwargs: QuickUMLS keyword arguments (see QuickUMLS in core.py) - """ - - self.quickumls = QuickUMLS(quickumls_fp, - # By default, the QuickUMLS objects creates its own internal spacy pipeline but this is not needed - # when we're using it as a component in a pipeline - spacy_component = True, - **kwargs) - - # save this off so that we can get vocab values of labels later + def __init__(self, nlp, quickumls_fp, best_match=True, ignore_syntax=False, **kwargs): + for cls, name, default in ((Doc, 'quickumls', None), (Span, 'similarity', -1.0), + (Span, 'semtypes', -1.0)): + if not cls.has_extension(name): + cls.set_extension(name, default=default) + elif cls.get_extension(name) != (default, None, None, None): + raise ValueError(f"Incompatible spaCy extension: {cls.__name__}._.{name}") self.nlp = nlp - - # keep these for matching + self.quickumls = QuickUMLS(quickumls_fp, spacy_component=True, **kwargs) self.best_match = best_match self.ignore_syntax = ignore_syntax - # let's extend this with some proprties that we want - Span.set_extension('similarity', default = -1.0) - Span.set_extension('semtypes', default = -1.0) - def __call__(self, doc): - # pass in the document which has been parsed to this point in the pipeline for ngrams and matches - matches = self.quickumls._match(doc, best_match=self.best_match, ignore_syntax=self.ignore_syntax) - - # Convert QuickUMLS match objects into Spans - for match in matches: - # each match may match multiple ngrams - for ngram_match_dict in match: - start_char_idx = int(ngram_match_dict['start']) - end_char_idx = int(ngram_match_dict['end']) - - cui = ngram_match_dict['cui'] - # add the string to the spacy vocab - self.nlp.vocab.strings.add(cui) - # pull out the value - cui_label_value = self.nlp.vocab.strings[cui] - - # char_span() creates a Span from these character indices - # UMLS CUI should work well as the label here - span = doc.char_span(start_char_idx, end_char_idx, label = cui_label_value) - # add some custom metadata to the spans - span._.similarity = ngram_match_dict['similarity'] - span._.semtypes = ngram_match_dict['semtypes'] - doc.ents = list(doc.ents) + [span] - - return doc \ No newline at end of file + entities = list(doc.ents) + groups = self.quickumls._match(doc, best_match=False, ignore_syntax=self.ignore_syntax) + selected = self.quickumls._select_terms(groups, ((e.start_char, e.end_char) for e in entities)) + doc._.quickumls = selected if self.best_match else groups + for group in selected: + top = group[0] + span = doc.char_span(top['start'], top['end'], label=top['cui']) + if span is not None: + span._.similarity = top['similarity'] + span._.semtypes = top['semtypes'] + entities.append(span) + doc.ents = entities + return doc diff --git a/quickumls/toolbox.py b/quickumls/toolbox.py index 3c7ea34..74724d8 100644 --- a/quickumls/toolbox.py +++ b/quickumls/toolbox.py @@ -12,7 +12,6 @@ # installed modules import numpy -import leveldb try: import unqlite UNQLITE_AVAILABLE = True @@ -240,6 +239,15 @@ def __init__(self, path, database_backend='leveldb'): self.semtypes_db_put = self.semtypes_db.store self.semtypes_db_get = self.semtypes_db.fetch elif database_backend == 'leveldb': + try: + import leveldb + except ImportError as exc: + raise ImportError( + "This index uses LevelDB. Install the legacy backend with " + "python -m pip install 'quickumls[leveldb]' on a system " + "that supports the leveldb bindings, or build a new " + "UnQLite index from the source UMLS files." + ) from exc self.cui_db = leveldb.LevelDB(os.path.join(path, 'cui.leveldb')) self.cui_db_put = self.cui_db.Put self.cui_db_get = self.cui_db.Get diff --git a/requirements.txt b/requirements.txt index bae55f1..d1bd8b0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,3 @@ -leveldb>=0.193 numpy>=1.8.2 spacy>=3.0.6 unidecode>=0.4.19 diff --git a/setup.py b/setup.py index 35e23cd..3771a30 100644 --- a/setup.py +++ b/setup.py @@ -58,6 +58,7 @@ def setup_package(): url='https://github.com/Georgetown-IR-Lab/QuickUMLS', license=about['__license__'], install_requires=requirements, + extras_require={'leveldb': ['leveldb>=0.193']}, dependency_links=dependency_links, classifiers=[ "Programming Language :: Python :: 3", diff --git a/tests/fixtures/corpora/stopwords/english b/tests/fixtures/corpora/stopwords/english new file mode 100644 index 0000000..3f048da --- /dev/null +++ b/tests/fixtures/corpora/stopwords/english @@ -0,0 +1,2 @@ +a +the diff --git a/tests/fixtures/umls/MRCONSO.RRF b/tests/fixtures/umls/MRCONSO.RRF new file mode 100644 index 0000000..7554e0c --- /dev/null +++ b/tests/fixtures/umls/MRCONSO.RRF @@ -0,0 +1,10 @@ +C1|ENG|||||Y|||||TEST|||amber|||| +C2|ENG|||||Y|||||TEST|||amber stone|||| +C3|ENG|||||Y|||||TEST|||the|||| +C4|ENG|||||N|||||TEST|||café|||| +C4|ENG|||||Y|||||TEST|||CAFÉ|||| +C5|ENG|||||Y|||||TEST|||café|||| +C4|ENG|||||Y|||||TEST|||café|||| +C6|ENG|||||Y|||||TEST|||stone|||| +C7|ENG|||||Y|||||TEST|||amber, pebble|||| +C1|SPA|||||Y|||||TEST|||ámbar|||| diff --git a/tests/fixtures/umls/MRSTY.RRF b/tests/fixtures/umls/MRSTY.RRF new file mode 100644 index 0000000..e0873f0 --- /dev/null +++ b/tests/fixtures/umls/MRSTY.RRF @@ -0,0 +1,8 @@ +C1|T047||||| +C2|T047||||| +C3|T184||||| +C4|T047||||| +C4|T184||||| +C5|T184||||| +C6|T047||||| +C7|T047||||| diff --git a/tests/prepare_sandbox.py b/tests/prepare_sandbox.py new file mode 100644 index 0000000..2e86593 --- /dev/null +++ b/tests/prepare_sandbox.py @@ -0,0 +1,73 @@ +"""Build .sandbox/META from the user's UMLS Metathesaurus full-release ZIP.""" + +import argparse +import io +from pathlib import Path, PurePosixPath +from tempfile import TemporaryDirectory +from zipfile import ZipFile + + +SANDBOX = Path(__file__).resolve().parents[1] / ".sandbox" +# Ordinary search inputs exercise overlapping mentions, drugs, symptoms, and Unicode. +TERMS = { + "aspirin", "chest pain", "pain", "headache", "heart", "heart failure", + "congestive heart failure", "diabetes mellitus", "type 2 diabetes mellitus", + "vitamin a", "sjögren syndrome", "sjögren's syndrome", "ménière disease", + "ménière's disease", +} + + +def prepare(archive_path): + SANDBOX.mkdir(exist_ok=True) + with ZipFile(archive_path) as archive, TemporaryDirectory(dir=SANDBOX) as temp: + inputs = [PurePosixPath(name) for name in archive.namelist() + if PurePosixPath(name).name == "MRCONSO.RRF"] + if len(inputs) != 1: + raise ValueError("Expected one MRCONSO.RRF in the Metathesaurus ZIP") + conso = inputs[0] + sty = conso.with_name("MRSTY.RRF") + archive.getinfo(str(sty)) # Both files must come from the same release. + + stage = Path(temp) + cuis = set() + found_terms = set() + atom_count = 0 + with archive.open(str(conso)) as member, (stage / conso.name).open("wb") as out: + for row in io.BufferedReader(member, buffer_size=1024 * 1024): + fields = row.split(b"|", 15) + if fields[1] == b"ENG": + term = fields[14].decode("utf-8").casefold() + if term in TERMS: + out.write(row) + cuis.add(fields[0]) + found_terms.add(term) + atom_count += 1 + missing = {"aspirin", "chest pain", "pain", "headache"} - found_terms + if missing: + raise ValueError(f"Missing core sandbox terms: {', '.join(sorted(missing))}") + + typed_cuis = set() + type_count = 0 + with archive.open(str(sty)) as member, (stage / sty.name).open("wb") as out: + for row in io.BufferedReader(member, buffer_size=1024 * 1024): + cui = row.partition(b"|")[0] + if cui in cuis: + out.write(row) + typed_cuis.add(cui) + type_count += 1 + if typed_cuis != cuis: + raise ValueError(f"Missing MRSTY rows for {len(cuis - typed_cuis)} CUIs") + + destination = SANDBOX / "META" + destination.mkdir(exist_ok=True) + for name in (conso.name, sty.name): + (stage / name).replace(destination / name) + print(f"Wrote {atom_count} English atoms and {type_count} semantic type rows " + f"for {len(cuis)} CUIs to {destination}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("archive", type=Path, help="Path to the licensed UMLS full-release ZIP") + args = parser.parse_args() + prepare(args.archive) diff --git a/tests/standin.py b/tests/standin.py new file mode 100644 index 0000000..dc49159 --- /dev/null +++ b/tests/standin.py @@ -0,0 +1,40 @@ +"""Query the fictional test vocabulary with: python tests/standin.py "amber stone".""" +import subprocess +import sys +from contextlib import contextmanager +from pathlib import Path +from pprint import pprint +from tempfile import TemporaryDirectory +from unittest.mock import patch + +import nltk +import spacy +from nltk.corpus.reader import WordListCorpusReader + +from quickumls import QuickUMLS, constants + +FIXTURES = Path(__file__).resolve().parent / 'fixtures' + + +def build_index(index, *flags): + index.mkdir() + subprocess.run([sys.executable, '-m', 'quickumls.install', '--skip-spacy', *flags, + str(FIXTURES / 'umls'), str(index)], check=True, stdout=subprocess.DEVNULL) + + +@contextmanager +def standin_index(): + with TemporaryDirectory() as tmp: + index = Path(tmp) / 'index' + build_index(index, '-L', '-U') + model = Path(tmp) / 'english' + spacy.blank('en').to_disk(model) + with patch.object(nltk.data, 'path', [str(FIXTURES)]): + words = WordListCorpusReader(str(FIXTURES / 'corpora/stopwords'), ['english']) + with patch('nltk.corpus.stopwords', words), patch.dict(constants.SPACY_LANGUAGE_MAP, ENG=str(model)): + yield index + + +if __name__ == '__main__': + with standin_index() as index: + pprint(QuickUMLS(index).match(' '.join(sys.argv[1:]) or 'amber stone')) diff --git a/tests/test_index.py b/tests/test_index.py new file mode 100644 index 0000000..2d5ba4b --- /dev/null +++ b/tests/test_index.py @@ -0,0 +1,136 @@ +import io +import os +import unittest +from collections import defaultdict +from contextlib import ExitStack, redirect_stderr +from pathlib import Path +from unittest.mock import patch + +import spacy +from spacy.tokens import Span +from unidecode import unidecode + +from quickumls import QuickUMLS, server +from quickumls import spacy_component # Register the spaCy factory. +from standin import FIXTURES, build_index, standin_index + +SANDBOX = Path(__file__).resolve().parents[1] / '.sandbox' + + +class BuiltIndex(unittest.TestCase): + @classmethod + def setUpClass(cls): + stack = ExitStack() + cls.addClassCleanup(stack.close) + cls.index = stack.enter_context(standin_index()) + cls.matcher = QuickUMLS(cls.index, threshold=1) + cls.addClassCleanup(delattr, cls, 'matcher') + + def test_match_flags(self): + cases = [({}, ['amber stone']), + ({'best_match': False}, ['amber', 'amber stone', 'stone']), + ({'ignore_syntax': True}, ['amber stone', 'the']), + ({'best_match': False, 'ignore_syntax': True}, ['amber', 'amber stone', 'stone', 'the'])] + for flags, terms in cases: + with self.subTest(flags=flags): + matches = self.matcher.match('amber stone the', **flags) + self.assertCountEqual([g[0]['term'] for g in matches], terms) + self.assertEqual(len(self.matcher.match('amber', best_match=False)), 1) + self.assertEqual(self.matcher.match('amber, pebble')[0][0]['term'], 'amber') + self.assertEqual(self.matcher.match('amber, pebble', ignore_syntax=True)[0][0]['term'], 'amber, pebble') + + def test_index_round_trip(self): + hits = self.matcher.match('A CAFÉ.')[0] + self.assertCountEqual([(h['cui'], h['semtypes'], h['preferred']) for h in hits], + [('C4', {'T047', 'T184'}, 0), ('C5', {'T184'}, 1)]) + self.assertTrue(all((h['start'], h['end'], h['similarity']) == (2, 6, 1) for h in hits)) + self.assertEqual(self.matcher.match('ámbar'), []) + + def test_distinct_unicode_spellings(self): + index = self.index.parent / 'unicode-index' + build_index(index, '-L') + db = QuickUMLS(index, spacy_component=True).cuisem_db + self.assertCountEqual([(cui, pref) for cui, _, pref in db.get('café')], + [('C4', 0), ('C4', 1), ('C5', 1)]) + + def test_custom_model(self): + model = self.index.parent / 'model' + spacy.blank('de').to_disk(model) + matcher = QuickUMLS(self.index, spacy_model=model) + self.assertEqual(matcher.nlp.lang, 'de') + self.assertEqual(matcher.match('amber')[0][0]['cui'], 'C1') + with self.assertRaisesRegex(OSError, 'quickumls_missing_model'): + QuickUMLS(self.index, spacy_model='quickumls_missing_model') + + def test_server_filter(self): + for args, cuis in [([], {'C4', 'C5'}), (['--accepted-semtypes', 'T047'], {'C4'})]: + with patch.object(server, 'run_server') as serve: + server.run_quickumls_server(server.parse_args([str(self.index)] + args)) + hits = serve.call_args.args[0].match('café')[0] + self.assertEqual({h['cui'] for h in hits}, cuis) + with redirect_stderr(io.StringIO()), self.assertRaises(SystemExit): + server.parse_args([str(self.index), '--accepted-semtypes', '047']) + + def test_spacy_entities_and_alternatives(self): + for _ in range(2): # Extensions are shared across independent pipelines. + nlp = spacy.blank('en') + with patch.object(spacy, 'load', side_effect=AssertionError('redundant model load')): + nlp.add_pipe('quickumls', config={'quickumls_fp': str(self.index), + 'options': {'best_match': False, 'threshold': 1.0}}) + doc = nlp.make_doc('amber stone café') + doc.ents = [Span(doc, 0, 1, label='EXISTING')] + nlp(doc) + self.assertEqual([(e.text, e.label_) for e in doc.ents], + [('amber', 'EXISTING'), ('stone', 'C6'), ('café', 'C5')]) + self.assertEqual(doc.ents[-1]._.semtypes, {'T184'}) + self.assertEqual({h['cui'] for g in doc._.quickumls for h in g}, {'C1', 'C2', 'C4', 'C5', 'C6'}) + self.assertEqual([e.text for e in nlp('amber stone').ents], ['amber stone']) + + def test_fuzzy_overlap_policy(self): + for policy, winner in [('score', 'amber'), ('length', 'amber stony')]: + nlp = spacy.blank('en') + nlp.add_pipe('quickumls', config={'quickumls_fp': str(self.index), + 'options': {'overlapping_criteria': policy, 'threshold': 0.6}}) + self.assertEqual([e.text for e in nlp('amber stony').ents], [winner]) + + +class SourceIndex(unittest.TestCase): + def test_all_sampled_atoms_against_source(self): + full = os.environ.get('QUICKUMLS_TEST_FULL') == '1' + if full or os.environ.get('QUICKUMLS_TEST_LICENSED') == '1': + root = SANDBOX / 'full' if full else SANDBOX + index, meta, sample = root / 'index', root / 'META', SANDBOX / 'META' + else: + stack = ExitStack() + self.addCleanup(stack.close) + index = stack.enter_context(standin_index()) + meta = sample = FIXTURES / 'umls' + matcher = QuickUMLS(index, accepted_semtypes=None, threshold=1) + with (sample / 'MRCONSO.RRF').open(encoding='utf8') as rows: + fields = (row.split('|', 15) for row in rows) + spellings = {atom[14] for atom in fields if atom[1] == 'ENG'} + probes = {unidecode(term.lower()) for term in spellings} + expected = defaultdict(dict) + with (meta / 'MRCONSO.RRF').open(encoding='utf8') as rows: + for row in rows: + fields = row.split('|', 15) + if fields[1] == 'ENG': + term = unidecode(fields[14].lower()) + if term in probes: + expected[term].setdefault(fields[0], int(fields[6] == 'Y')) + self.assertEqual(set(expected), probes) + wanted = {cui for cuis in expected.values() for cui in cuis} + types = defaultdict(set) + with (meta / 'MRSTY.RRF').open(encoding='utf8') as rows: + for row in rows: + cui, tui, _ = row.split('|', 2) + if cui in wanted: + types[cui].add(tui) + self.assertTrue(spellings) + for term in sorted(spellings): + with self.subTest(term=term): + cuis = expected[unidecode(term.lower())] + groups = matcher.match(term, best_match=False, ignore_syntax=True) + hits = [h for g in groups for h in g if (h['start'], h['end']) == (0, len(term))] + self.assertCountEqual([(h['cui'], h['semtypes'], h['preferred']) for h in hits], + [(cui, types[cui], pref) for cui, pref in cuis.items()])