Session API#
Session is the entry point: from isocenter import Session. It is the
class isocenter.session.DicomSession, rendered below. Its constructor
and every method on this page are frozen at 1.0
(API stability). So are the attributes in its table,
except store_backend, which is tier 2. This page lists the methods in
pipeline order, ingest → examine → config → audit → anonymize → redact →
verify → export → report. compact, release_memory and close come
last. Results and errors says what the methods return and
raise.
Session#
- Session(persistence_file=None)#
The session: an indexed store of DICOM files and the de-identification pipeline over it.
Import it as
from isocenter import Session. Use it in awithblock, or callclose(), because an open session holds a worker pool and two threads.Attributes:
Name
Type
Description
storeDicomStore
The object graph.
store.patientsis theList[Patient]ofPatient->Study->Series->Instance.configurationThe configuration that
audit(),anonymize(),redact()andexport()apply.store_backendThe session’s SQLite store. Its
get_audit_*methods read the audit trail.persistence_filestr
The store’s path, or
":memory:".Open the session store at
persistence_file, creating it if needed.The store is the SQLite file and a pixel file beside it (by default
isocenter.dbandisocenter_pixels.bin). It holds the original identifiers and pixels of everything ingested. Keep it where you keep the source data, on a local filesystem. The store uses SQLite’s WAL mode andflocklocks, which a network filesystem does not dependably support.When the store’s filesystem is a known network type (NFS, SMB, Lustre, GPFS and others), one
WARNINGlog line says so, and the store opens anyway. Untilexport(), the session writes only the store,isocenter.logand the files that you ask for (a configuration, a key).When a file named
isocenter.keyexists in the current working directory, the session callsenable_reversible_anonymization()with it. The path is resolved to an absolute path at construction. With no such file, reversible anonymization stays off and no key is created.- Parameters:
persistence_file (str) – Path to the SQLite database file for session persistence. The default is
ISOCENTER_DB_PATH, then"isocenter.db".":memory:"is accepted and is part of the frozen surface. With it, the index lives in memory, and the pixel sidecar lives in a temporary file that the store unlinks onclose(). On such a store,redact()runs in threads on every interpreter, because its worker writes to the store and a process cannot share an in-memory database. WithISOCENTER_MAX_TASKS_PER_CHILDset, recycling overrides that and the call fails. See that variable on the Environment Variables page.- Raises:
ValueError – If
isocenter.keyin the working directory is empty, is not a Fernet key, or is not a regular file (a directory, a FIFO). The message names its absolute path. The threads that the session had started are released before the error is raised, as they are for any exception from construction.
- ingest(directory: str)#
Ingest every DICOM file under a directory into the session store.
It walks
directoryrecursively, reads each DICOM file into the Patient -> Study -> Series -> Instance hierarchy, and saves the session when it finishes.A file that cannot be ingested does not raise. It is counted in the returned summary, and it gets an
ERRORaudit row that names the path and the reason. That row bars aPASSgrade. Check the return value, because a run that rejected files completes normally.A file can be refused after its pixels or waveform samples were read (
Linkage Failed). Such a file may leave them in the sidecar as dead space untilcompact(), which reclaims them in a store that holds at least one instance (#943).A file linked by something that is not one text value. A file is linked by its SOP Instance UID, Study Instance UID, Series Instance UID and Patient ID. A file is rejected as above when it holds two values in any of them (#747). It is also rejected when it states a VR for one of them that is not text (
OB,US,DS,SQand the like, in an Explicit VR file, #1022). Only that file is rejected. Its reason names the element and the count or the VR, never a value, and nothing of the file is in the sidecar. Until #1022, a SOP Instance UID or Patient ID under such a VR made this call raiseValueErrorfrom its save and store nothing.Hidden files. A file that the walk of
directoryfinds, whose name starts with.(.DS_Store, AppleDouble._*), is not read. It is counted inIngestSummary.hidden, and the console summary prints the count, with no audit row. A directory whose name starts with.is walked, and a file named directly asdirectoryis read whatever its name.A file that ends the worker process reading it (the out-of-memory killer, a decoder crash,
SIGKILL) is read again alone on a fresh worker. It is rejected only if it ends that worker too. Files already read are kept. A death that does not recur costs no file and logs oneWARNINGline.When a worker ends, the pool’s other workers are sent
SIGTERM. A worker that is still running 10 s afteringest()finds the pool broken is sentSIGKILL, and oneWARNINGline names it. A worker of a script that handlesSIGTERMcan be such a worker. If fresh workers cannot run at all, every file left is rejected as “Not read”, with a reason that names the usual causes (a script without theif __name__ == "__main__":guard among them). The call then returns. Any other failure of the worker pool raises.Duplicate SOP Instance UIDs. A file is declined when an instance in this session already holds its SOP Instance UID. That instance was ingested earlier in this call, by an earlier call, or loaded from the store. For a declined file:
the instance is kept
the file is not read into the store
the file is counted in
IngestSummary.declineda
WARNINGaudit row names the UID, the file, and the file that the instance was ingested from
An instance that the session already holds is always kept over a new file. Among files new to this call, the one whose path sorts first is kept, whatever order the filesystem lists them in. The sort is on the path string as walked (
os.path.joinof the directory and the name), which is the string that theWARNINGrow prints. A declined file is not recorded as imported, so a second ingest of the same folder declines it again.A study another patient holds. A file that carries a Patient ID is declined the same way, and in the same order, when a patient with a different Patient ID already holds its Study Instance UID (#745). Its
WARNINGrow names the file and the instance, never a Patient ID. A file that carries the original ID of the patient whose studyanonymize()renamed belongs to that patient, and is linked. A file with no Patient ID belongs to that patient too, and is linked.Byte order. A big-endian source’s values in words wider than a byte (
OW,OL,OF,OD,OVand the waveform samples) are stored little-endian, as its pixels are. A value that cannot be converted whole (aUNvalue, a length that is not a whole number of words, samples with no usable Waveform Bits Allocated) is kept as read, and it gets oneWARNINGaudit row per element.Environment.
ISOCENTER_FORCE_THREADSandISOCENTER_MAX_TASKS_PER_CHILDhave no effect, because ingest runs on the session’s own process pool, which has no threads mode and never recycles a worker. When either is set, each call that has files to read logs oneWARNING.ISOCENTER_MAX_WORKERSis read on every call, and the pool is rebuilt when the width has changed. An unchanged width rebuilds nothing. While anotheringest()in this session is running on the pool, a changed width is reported in oneWARNING, and this call runs at the pool’s current width.Concurrency.
compact()on any thread of this session raises while an ingest runs. While acompact()is saving or rewriting, this call waits (bounded, seeRaises) and then proceeds. A file whose pixels cannot be written in that time is rejected like any other failed file, with anERRORaudit row that names the path and the reason.- Parameters:
directory (str) – The path to the directory containing DICOM files.
- Returns:
How many files reached the store, and
(path, reason)for each one that did not.- Return type:
- Raises:
RuntimeError – If the ingest cannot start within 180 s because a
compact()is still saving or rewriting the sidecar.
- save(sync: bool = False)#
Persist the current session state to the store.
Without
sync=True, the save is queued and this method returns before the save is written, so a failure is not raised here. The failure is logged at ERROR, and the next call that drains the queue then hears it.audit(),redact(),lock_identities()andlock_identities_batch()run the failed save again themselves and raise what it raises. A failure that has passed heals there silently.save(sync=True),export()andcompact()save the session themselves and raise the same way.A session can close, or its process can exit, with a failed background save that no later save healed. Then one
ERRORaudit row keyedSESSIONis written, so a later session’s report on the store gradesREVIEW_REQUIRED(#941).- Parameters:
sync (bool) – If True, block until the save is complete. A synchronous save first waits for the persistence manager’s queue, and never returns early: a background save that does not finish blocks it.
- examine()#
Prints a summary of the session contents and equipment.
- create_config(output_path: str)#
Generates a unified configuration file (scaffold) in YAML format.
It reads the session inventory, pre-fills redaction rules for any machine that the shipped knowledge bases recognise, adds the default PHI tag policy, and writes the result as commented YAML.
- Parameters:
output_path (str) – Where to write the generated YAML. A
.yamlsuffix is appended if missing.
The
phi_tagssection names the session’s own base, assave()does. It holds every rule that differs from the rules of that base, compared whole (#741). The file names the base asprivacy_profile: nonefor a session undernone, as the external file’s path for an external profile, and as the pinned name for a built-in. The floor is the one exception. It is spelledprivacy_profile: basic@2026c, with the research defaults as editable lines, and that loads to the same rules. The file loads to the session’sphi_tags.- Raises:
ValueError – If
configuration.date_jitteris a range that the loader would refuse in the file (#731). Alsosave()’s refusals: ifphi_tagslacks a rule that its base supplies (#741), or ifoutput_pathis a file that declares a newerversionminor than this library’s (#784). Also ifconfiguration.burned_in_textis a policy that the loader would refuse in a file (#1108). In each case, nothing is written.OSError – The write’s own error, after it is logged (#741).
- load_config(config_file: str)#
Load a configuration file as the session’s configuration.
A load changes no data.
preview_config()shows which instances its redaction rules match.audit(),anonymize()andredact()apply it.- Parameters:
config_file (str) – Path to the YAML configuration file.
- Raises:
FileNotFoundError – If
config_filedoes not exist.ValueError – If the file fails validation: not
.yaml/.yml, YAML syntax, a root that is not a mapping, aversionthis library does not read, a key the schema does not have at any level, a value of the wrong type, an unknownprivacy_profile(including a<profile>@<edition>this version does not ship), an unknownaction, aphi_tags,date_jitterormachinesof the wrong shape, an invalid machine rule, or aphi_tagsrule the pipeline cannot honour. After either error the configuration is exactly what it was before the call.
- preview_config()#
Runs a dry run of the currently loaded configuration.
It checks the active redaction rules against the current session inventory, and prints a summary of the instances that the rules would affect (match). It does not change any data.
- audit(config_path: str = None) PhiReport#
Scan every patient in the session for PHI under a tag policy.
The policy is the file at
config_pathwhen one is given, and otherwisesession.configuration.phi_tags. The scan runs in parallel worker processes.Before the scan, two
Patientobjects that hold one Patient ID are merged into the one that was in the session first. Sostore.patientscan get shorter, as afteranonymize().The scan records every status with the policy that it ran under. That is the configuration’s policy, or, with
config_path, that file’s rules under this session’sremove_private_tags. An entity whose status is unchanged but whose policy differs is recorded again, so the nextsave()writes it.- Parameters:
config_path (str, optional) – Path to a configuration file whose PHI rules to scan with.
- Returns:
The findings: iterable, indexable, and convertible with
to_dataframe().- Return type:
- Raises:
ValueError – If the file at
config_pathfails any check thatload_config()makes. If the policy (that file’s, orconfiguration.phi_tags) holds a rule that the pipeline cannot honour. With noconfig_path, ifconfiguration.date_jitteris a range that the loader would refuse in a file (#731). In each case, it is raised before a project secret is created.RuntimeError – If patients that share a Patient ID were de-identified under different date-offset schemes, so they cannot be merged. It is raised after the policy is validated, and before anything is scanned or a project secret is created. Also on a store that holds dates shifted under a project secret that it no longer has.
Exception – If a background
save()failed and still fails. The entry drain runs that save again and raises what it raises (the store’s namedTypeErrororValueError, anOSError, the sidecar gate’sRuntimeError), before anything is scanned. A failure that has passed is saved there, and nothing is raised (#941).
- auto_remediate_config(report: PhiReport) int#
Reads the given OCR report, and updates the session’s configuration to fix the leaks that the report found (by expanding zones or adding new ones).
- Parameters:
report (PhiReport) – The findings from .scan_pixel_content()
- Returns:
The number of changes applied.
- Return type:
int
- anonymize(findings: List[PhiFinding] = None)#
Apply the remediation each PHI finding proposes (tag anonymization).
With
findings, only those findings are remediated. An empty list, tuple,PhiReportor iterator applies nothing and returns 0, because a filtered report that matched nothing is not a request to remediate everything. Onlyfindings=None, or no argument, runs a fullaudit()under the current configuration and remediates every finding that it raises. An empty call still reads the store’s project secret, so a store that has lost the secret refuses and does not return 0.Nothing outside
session.storeis written. A finding whoseentityis itself in the graph is acted on as it is, with one exception. For aREMOVE_TAG, “already gone” is read on the object at the finding’s address, and the finding declines where that object andentitydiffer. Any other finding is resolved against the live graph at itsentity_uidandentity_path, and acts on the object found there. Thatentity_uidmay be an instance’s UID from beforeredact(), or a patient’s original Patient ID after the pseudonym that this store minted for it. Because the finding acts on the live object, a report kept acrossclose()and a reopen cleans the graph thatexport()writes.A finding whose address names no single object declines. A finding inside a sequence that a pass already removed or emptied is satisfied. A Patient ID is written, and a date is shifted, only with a value that belongs to the live patient that holds it (this store’s pseudonym, and an offset seeded on that patient under its own scheme). Otherwise the finding declines. The findings passed are not modified.
A patient, study or instance edited after its last scan and before this pass is not stamped by the pass. It keeps the status that the scan left, and still reads
UNSCANNEDafterwards. So it grades under condition 8 untilaudit()reads the edit (#752).Two patients can be left holding one Patient ID (a study ingested under a patient’s original ID after that patient was anonymized). They are merged into whichever was in the session first, and the other is removed from
store.patients.- Parameters:
findings (List[PhiFinding], optional) – Specific findings to clean.
- Returns:
How many remediations were applied. Failures are logged and excluded, so a caller can tell a clean run from a partial one.
- Return type:
int
- Raises:
ValueError – If
configuration.date_jitteris a range that the loader would refuse in a file (#731). It is raised first, before anything is scanned or shifted.RuntimeError – If two patients left holding one Patient ID were de-identified under different date-offset schemes. It is raised at the merge, after the remediations are applied. It cannot occur on a graph that the library built, but it can occur on one built in user code.
Exception – With no
findings, whatever the startingaudit()raises, including a failed backgroundsave()that still fails (#941). It is raised before anything is remediated. Given its findings, the method makes no such call and does not raise that.
- enable_reversible_anonymization(key_path: str = 'isocenter.key')#
Turn on reversible anonymization with the key file at
key_path.It loads the key when a file is there. This call never creates the key file, and neither does recovery. The first
lock_identities()that writes a token creates it when none exists. So a mistyped path beforerecover_patient_identity()fails there withFileNotFoundError, and does not mint a key that the data was never locked under.- Parameters:
key_path (str) – Path to the key file.
- Raises:
ValueError – If the file at
key_pathis not a Fernet key, or is empty, or the path is not a regular file (a directory, a FIFO). The message names the path. A failed enable caches nothing, and the session stays open and usable. Fix the file and enable again.
- lock_identities(patient_id: str, persist: bool = False, *, verbose: bool = True, tags_to_lock: List[str] | None = None) List[Instance] | LockingResult#
Encrypt each instance’s original identifiers into an identity token carried in the instance, for reversible anonymization.
The token is written into the Encrypted Attributes Sequence
(0400,0500), under the key thatenable_reversible_anonymization()names. Values are captured from each instance, and one token is written per distinct set of them. So under the default tags, a patient with several studies carries about one token per study. Each instance’s token holds that instance’s own values.If recovery is required, call it before
anonymize(). Afteranonymize(), the identifying tags no longer hold their original values, and the lock refuses to capture what a remediation wrote.Anything but a
str(an iterable of Patient IDs, aPhiReportor a list of findings) is handed tolock_identities_batch(), with the samepersist,verboseandtags_to_lock.auto_persist_chunk_sizeis that method’s own argument.Refusals. The lock raises
RuntimeErrorand writes no token when the patient cannot be locked as asked:A remediation wrote a value that the lock would capture (
ANONYMIZED,ANON_..., a rule’svalue:, a shifted date).anonymize()emptied or removed a tag that the lock names, on any of the patient’s instances. The message names thetags_to_lockthat works without that tag. Where other instances still hold a value there (a study or series ingested after the pass), the message counts both, and that lock stashes the tag for none of them.A re-lock would lose a value that the existing token holds.
The patient carries an identity token that this library wrote, and one of these is true of the token: the key at the path given to
enable_reversible_anonymization()does not decrypt it, it opens to no identity record, or it is in the layout that releases before 1.0 wrote, which 1.x does not read.A re-lock over a token that this store did not write (one that arrived inside a file, or one that a release before 0.9.8 wrote) would change a value that the token holds. The message names the tag, which need not be one that
tags_to_locknames. The way through isrecover_patient_identity(..., restore=True), followed by a lock.A value that the lock would capture is one that no token can hold (
bytes). The message names the tag.Patient’s Name is blank under a rule of EMPTY or REMOVE on it.
The patient holds a Patient ID (or a Patient’s Name), and every instance’s copy of
0010,0020(or0010,0010) is present and blank. The message names the tag. The token would restore the patient without it (#761).The patient has instances, and any of them holds no value in any tag that
tags_to_locknames (ortags_to_locknames none). The message counts them. For0010,0010and0010,0020, the lock reads the patient’s value when an instance holds none. A tag held blank is a value, except as the refusal above says. A patient with no instances locks as 0 instances.
Each of these is judged on every instance’s own values, so a value that a pass wrote on any study refuses the lock. An existing token is judged against the first instance that carries it. Before any patient is planned, the lock also refuses when no key file exists at the path and an instance in the session carries a token that this library wrote. No key is created then. Given a list or a report, every patient is checked first. If any is refused, one error lists each refused patient, and no patient is locked.
No message carries a Patient ID. A message says “this patient”, its advice spells the ID
<its Patient ID>, and a replaced Patient ID is described, not quoted.Only a lock that writes a token creates the key file (the first such lock under a path with none). It creates the file after every patient is planned, already written and with mode 0600. A lock that writes no token (refused, no patient found, or none with an instance) creates no key file (#813).
- Parameters:
patient_id (str) – The ID of the patient to lock. Anything that is not a
str(a list, set, frozenset or iterator of IDs, or a report) is handed tolock_identities_batch().persist (bool) – If True, writes each instance’s token immediately into the row that the store holds for it. An instance that the store holds no row for raises (see
RuntimeError). If False, returns the modified instances for a latersave().verbose (bool) – If True, logs debug information.
tags_to_lock (List[str], optional) – The tags whose original values are embedded. When omitted: PatientName, PatientID, PatientBirthDate, PatientSex and AccessionNumber.
- Returns:
A list of modified instances.
- Return type:
Union[List[Instance], LockingResult]
- Raises:
RuntimeError – If reversible anonymization is not enabled, or for a refusal above, before any token is written. Also, with
persist=True, if some instance’s current SOP Instance UID has no row in the store to write its token into. This happens for a patient built by hand and never saved, or for a UID thatregenerate_uid()moved (asredact()does) since the last save. That error is raised after the tokens are embedded. They are in memory and marked modified, so a latersave(sync=True)stores them. This write stored none of them, and oneERRORaudit row gives the counts.ingest()writes the rows itself, and the lock drains a save queued bysave()before it embeds anything. So neither ingest-then-lock norsave()-then-lock raises it.TypeError – If
patient_idis not astrand is not a selection thatlock_identities_batch()accepts:None, bytes-like, not iterable, or an iterable that holds an item that is neither astrnor a finding. It is raised before the key is loaded or created.ValueError – If the key file at the path is empty (the message names the path) or is not a Fernet key. Neither result is cached, so a later call reads the file again.
sqlite3.Error – With
persist=True, if the store refused the write. The instances already carry the new token in memory, marked modified, so a latersave()writes them. This write stored none of them, and oneERRORaudit row says so. The row speaks for the write, not for the store, which keeps whatever an earlier write put there. Given a list or a report, the batch form’ssqlite3.Errorapplies.Exception – If a background
save()failed and still fails. The lock’s drain runs that save again and raises what it raises, before any token is embedded. A failure that has passed is saved there, and nothing is raised (#941). The batch form does the same.
- lock_identities_batch(patient_ids: List[str] | PhiReport | List[PhiFinding], auto_persist_chunk_size: int = 0, tags_to_lock: List[str] | None = None, *, persist: bool = False, verbose: bool = True) List[Instance] | LockingResult#
Lock the identities of several patients. See
lock_identities().- Parameters:
patient_ids (Union[Iterable[str], PhiReport]) – The patients to lock: an iterable of Patient IDs (read once, so an iterator works), a
PhiReport, or an iterable of findings, which may be mixed with IDs. It is read as every other method readspatient_ids, except thatNoneis refused. There is no spelling for “lock every patient”, and the report thataudit()returns locks every patient that its scan found.auto_persist_chunk_size (int) – If > 0, persists changes and releases memory every N instances, and the call returns an empty list.
tags_to_lock (List[str], optional) – Passed to every patient’s lock. When omitted,
lock_identities()’s five default tags apply.persist (bool) – Passed to every patient’s lock: each patient’s instances are written as they are locked. With
auto_persist_chunk_size > 0as well, an instance is written twice (with its patient, then with its chunk), which is redundant, not wrong.verbose (bool) – Passed to every patient’s lock: one debug line per patient.
- Returns:
All modified instances, or an empty list when
auto_persist_chunk_size > 0.- Return type:
Union[List[Instance], LockingResult]
- Raises:
RuntimeError – If reversible anonymization is not enabled, or if any patient found cannot be locked as asked (the refusals that
lock_identities()lists). Every patient is checked before any is locked. So the one error lists each refused patient with its own message, in Patient ID order, and no patient is locked, whateverpersistorauto_persist_chunk_sizesays. A Patient ID that matches no patient is logged, not raised. The promise is about refusals, not about the store (seesqlite3.Error). No message names a patient. Each refusal is prefixed[n of m], its place among thempatients found, in Patient ID order. So the refused patient issorted(ids that matched a patient)[n - 1]. The refusal raised before any plan (no key file, and a token that this library wrote somewhere in the session) is one message with no number, and it creates no key.TypeError – If
patient_idsisNone, is a barestr(the single-ID spelling islock_identities(patient_id)), is bytes-like, is not iterable, or holds an item that is neither astrnor a finding. The message names such an item by its position and type, never by its value. It is raised before the key is loaded or created, and before any patient is planned.ValueError – If the key file is empty or is not a Fernet key, as for
lock_identities().Exception – If a background
save()failed and still fails. The lock’s drain runs that save again and raises what it raises, before any token is embedded, as forlock_identities()(#941).sqlite3.Error – If a store write failed while tokens were being persisted (
persist=Truewrites per patient,auto_persist_chunk_sizeper chunk). It is raised after oneERRORaudit row. A store write that found no row for an instance raisesRuntimeErrorinstead (seelock_identities()), with the same shape and timing. Both are raised after the tokens are embedded, unlike the refusals above. Nothing is rolled back across writes. Patients written before the failure stay locked in the store. The failed write stored none of its instances (they hold their new tokens in memory, marked modified, and a latersave()writes them). The patients after it in Patient ID order are not locked. One write is one transaction. With bothpersist=Trueandauto_persist_chunk_size, each instance is written with its patient and again with its chunk. So where a chunk write fails, its instances were already stored with their patients.
- recover_patient_identity(patient_id: str, restore: bool = True) Dict[str, Dict[str, Any]]#
Decrypt a patient’s identity tokens and return the identity they hold. With
restore=True, also write it back onto the patient.Which token speaks for the patient. It is the first token of ours in study, series and instance order. A study without a token, or with an Encrypted Attributes Sequence that this library did not write, is walked past. For a patient with a Patient ID, a first token that holds a blank Patient ID is passed over for the first token that holds a non-blank one, when there is one. For a subject with no Patient ID, its first token always speaks, and the subject keeps its key.
Every distinct token is opened before anything is written, with
restore=Falsetoo. A token of ours on any study that this key cannot open, or that holds no record, raises and writes nothing. Sorestore=Falsealso checks that the patient is recoverable under this key. Every failure raises. Nothing is printed, and no message names a Patient ID.What
restore=Truewrites. Every instance of the patient in memory takes the locked identity tags from the token that it carries. The restore is recorded, so a latersave()stores it. A patient that already holds the restored Patient ID is merged into whichever of the two was in the session first.Only the locked tags are put back. Every other date stays shifted by the patient’s offset, so intervals are intact and a later
audit()does not shift it again. A date among the locked tags is put back like any locked tag, and a lateraudit()raises it again.When the restored value reads as a date, a restored Study Date is also put back on each
Study, from that study’s own token.export()reads it there. A blank or unreadable value leaves theStudyas it is, with one WARNING per such study that carries no date.An instance that carries no token takes only the patient-level identifiers of the token that speaks for the patient. These are group 0010, which includes Patient’s Age, Size and Weight, and so may be another study’s. The instance keeps its other locked identifiers as the pass left them, and one WARNING gives the count. For a patient with no Patient ID, such an instance keeps a non-blank Patient ID of its own, and does not take the token’s blank one. A second WARNING counts those instances.
Where tokens disagree on Patient’s Name or Patient ID, each instance keeps its own and the
Patienttakes the speaking token’s, with a WARNING. A token whose Patient ID is blank does not disagree on it.
- Parameters:
patient_id (str) – The Patient ID the patient holds now (normally its pseudonym).
restore (bool) – If True, write the recovered identity back, as above. If False, write nothing.
- Returns:
The identity recovered. Each key is the SOP Instance UID of an instance that carries an identity token of ours, as the UID was when the call began. Each value is a deep copy of the values that the instance’s token holds, keyed
"gggg,eeee", in study, series and instance order. An instance that carries no token is absent, and the dict is never empty (a patient with no token raises). Both modes return the same mapping, taken beforerestore=Truewrites anything. It is what the tokens hold, not what the restore wrote, so a tokenless instance to which a restore gives group 0010 of the first token is absent. The patient-level answer (the token whose name and ID a restore stamps on thePatient) isnext(iter(result.values())). Two instances that share one SOP Instance UID, which only a hand-built graph can hold, share one key, and the later instance’s token is the value. These are the original identifiers, handed to the holder of the key. Nothing prints or logs them.- Return type:
Dict[str, Dict[str, Any]]
- Raises:
FileNotFoundError – If there is no key file at the path given to
enable_reversible_anonymization(). This is checked first, before the patient is looked up, and no key is created.ValueError – If no patient in this session holds
patient_id. Also if the key file is empty or is not a Fernet key. The key file is read before the patient is looked up, and it is not cached.RuntimeError – If reversibility is not enabled. If the patient has no instances, or no instance that carries an identity token (an Encrypted Attributes Sequence that did not come from this library counts as no token, not as the wrong key). If the key does not decrypt the token, or the key opens it but it holds no identity record that this library writes, or the token was written by a later release of this library. If an instance’s token is in the layout that releases before 1.0 wrote, the token in
(0400,0510), which 1.x does not read. Withrestore=True, if a patient that holds the restored Patient ID was de-identified under a different date-offset scheme. That case is raised before anything is restored.
- redact(show_progress=True, force=False)#
Apply the configured pixel redaction zones to every matching image.
It uses
session.configuration.rules. Every image of a series that a rule covers, by its Device Serial Number or bymatch:, has each of the rule’s zones set to zero. This changes pixel data in memory (and the sidecar, for persistence). Callsave()afterwards to persist it.An image that several rules match (an exact rule and
"*") is redacted once, with the zones of every matching rule. A redacted instance takes a new SOP Instance UID. The UID is derived from its source SOP Instance UID and the zones of every rule that matches it, whatever order the work runs in.The
burned_in_textpolicy (configuration.burned_in_text, #1108). When the configuration holds one, this call also reads every instance in the policy’sscope, serial or not, after the zones its rules hold. It reads with OCR by tesseract, or with the text detector underdetector: db. The scope isflagged,modalitiesorall(#1121). An instance out of scope is neither read nor gated at export. The call records the boxes of the text that it finds atmin_confidenceor above (under tesseract, with two letters or digits), never the text itself. The policy’sactiondecides the rest:redactblanks each box, padded, on its own frame, in the same task as the zones. The instance’s UID is derived from the zones and the boxes.reportwrites oneWARNINGaudit row per instance with text, and changes no pixel.withholdchanges nothing here, andexport()withholds each instance with text.
The record names, by a digest, the pixels that the read saw. An instance already read under this threshold and these zones, whose pixels still match the digest, is not read again unless
force=True. A redacted instance is read once more, which moves the digest to its redacted pixels. A failure of that read writes aWARNINGrow and leaves the instance unchecked. Text still found writes aWARNINGrow.An instance that only this policy redacted carries
DERIVEDand the derivation code, but keeps Burned In Annotation as the source had it. Every pass writes oneREDACTIONrow with its counts and what read: the tesseract version, or underdetector: dbthe detector model and the OpenCV version (with the tesseract version too under a narrowedtarget).redact_by_machine()does not run the policy.Concurrency.
compact()on any thread of this session raises while a pass runs. While acompact()is saving or rewriting, this call waits (bounded, seeRaises) and then proceeds. A worker whose pixels cannot be written in time comes back as a failed redaction, with anERRORaudit row.- Parameters:
show_progress (bool) – If True, displays a progress bar.
force (bool) – Redact again the instances already redacted under this configuration, instead of skipping them. Every instance that the rules match is redacted again. Its SOP Instance UID is derived again from its source SOP Instance UID and the zones of its matching rules. Unchanged zones give the UID and exported filename that it already has, and other zones give another.
file_pathbecomes None either way. Under aburned_in_textpolicy, also read every instance again, and keep every box that its record held beside the ones found now.
- Returns:
How many instances had at least one configured zone, or one
burned_in_textbox, applied to their pixels. An instance that a rule matched but whose every zone fell outside the image is not counted. A zone with no area fails its instance, and the pass raisesRedactionError, so that instance is never counted. Zero means that nothing was redacted: no rules loaded and noburned_in_textpolicy, no image matched one, every match was already redacted under this configuration, no zone landed, or the policy’s action isreportorwithhold.- Return type:
int
- Raises:
RedactionError – If any instance’s zone could not be applied. It is raised at the end of the pass, not at the first failure. By then the instances that could be redacted are redacted, the failures are already
ERRORrows in the audit log, and the console summary has been printed. So a caller that catches it still has a correct object graph and a compliance report that gradesREVIEW_REQUIRED..failurescarries(sop_uid, detail)per failed instance. It subclassesRuntimeError, soexcept RuntimeErrorcatches it and theRuntimeErrorexceptions below alike. A failed instance is left exactly as it was found: noDERIVEDflag, no record of the redaction, nothing persisted. So a corrected configuration retries it.Exception – Whatever the redaction backend raised, after it is logged. Also, before the pass starts, what a failed background
save()raises when its drain runs it again and it still fails. The drain comes after the call reads itsburned_in_textpolicy. A failure that has passed is saved there, and nothing is raised (#941). A call with no rules loaded and noburned_in_textpolicy returns 0 before that drain.ValueError – If
burned_in_textwas assigned in code to a policy thatload_config()would refuse in a file. It is raised before the drain.OcrUnavailableError – A
RuntimeError. It is raised when aburned_in_textpolicy is configured and a reader that the policy needs cannot run: tesseract (theocrextra and the binary) underdetector: tesseractor a narrowedtarget, the text detector underdetector: db(TextDetectorUnavailableError), or the names model whentargetnamesnames(NlpUnavailableError). Underdetector: dbwithtarget: any, tesseract is not needed. It is raised after the drain, and before any task, UID, pixel or row, zones included.RuntimeError – If the pass cannot start within 180 s because a
compact()is still saving or rewriting the sidecar. It is raised before any worker is dispatched and before any UID is regenerated, so there is nothing to undo.RuntimeError – On a
":memory:"store, when the environment asks for worker recycling (ISOCENTER_MAX_TASKS_PER_CHILD). A recycled worker is a process, and a process cannot reach an in-memory database. The message names the store, the variable, the cause and two remedies. It is raised after the persistence drain and before the pass-lock: no task is prepared, no SOP Instance UID is regenerated, no pixel is touched, and no audit row is written. It is not aRedactionError, because nothing was attempted.ISOCENTER_FORCE_PROCESSESdoes not raise. This call asks for threads, which outranks the variable, and aWARNINGnames the variable instead.
- redact_by_machine(serial_number: str, roi: List[int])#
Redact one zone on one machine’s images, without editing the configuration.
It replaces the configuration’s rules with one rule for
serial_numberthat holdsroi, and runsredact(). Then it restores the original rules, also whenredact()raises. Aburned_in_textpolicy is set aside and restored in the same way, so this call runs no OCR (#1108).- Parameters:
serial_number (str) – The device serial number to target. Use
""for every series with no Device Serial Number, and"*"for every series, as in a rule (#1108).roi (List[int]) – The Region of Interest as [y1, y2, x1, x2].
- Raises:
RedactionError – Propagated from
redact()if the zone could not be applied. The original rules are restored first.RuntimeError – Propagated from
redact(), which refuses a":memory:"store whose environment asks for worker recycling, and a pass-lock wait that expires. The original rules are restored first.Exception – Propagated from
redact()’s drain, if a backgroundsave()failed and still fails (#941). It is raised before anything is redacted. The original rules are restored first.
- scan_pixel_content(serial_number: str = None) PhiReport#
Scan instances for burned-in text with OCR, and report the text no configured redaction zone covers.
Only instances that meet two conditions are scanned:
A rule covers their machine, as
redact()reads it: by exact Device Serial Number, by""for a series with no serial, by"*", or bymatch:.The covering rules hold at least one valid zone.
Each instance is checked against the zones of every rule that covers it,
[y1, y2, x1, x2]and{"roi": [...]}alike. These are the zones thatredact()andexport()apply. When nothing is scanned, the printed line counts two groups separately: the instances of machines that no rule names, and the instances whose rules hold no zone.- Parameters:
serial_number (str, optional) – Scan only the machine with this serial number.
- Returns:
Findings for burned-in text that no zone covers. Each finding’s
entityis the liveInstanceinsession.store, whether the scan ran in threads or in processes. It isNonewhen that instance cannot be found in the graph, and it is never a worker’s copy.PhiReport.failureslists(entity_uid, reason)for each instance whose pixels could not be loaded or whose OCR raised on any frame, and aWARNINGlog line gives the count. Each failure is also oneWARNINGaudit row that names the instance and the reason, so the compliance report gradesREVIEW_REQUIRED. An instance with no pixel element is neither scanned nor a failure. A worker process runs thepytesseract.pytesseract.tesseract_cmdthat the caller set.- Return type:
- Raises:
RuntimeError –
pixel_analysis.OcrUnavailableErrorif theocrextra is not installed, or if thetesseractbinary does not answer in the calling process. It is raised before any worker is dispatched and before the graph is read.pixel_analysis.PixelScanError, which carries.failuresand.attempted, if at least one instance failed and none could be read. It is raised after the pass, the audit rows and the warning.
- discover_redaction_zones(serial_number: str, sample_size: int = 50, min_confidence: float = 80.0)#
OCR a random sample of one machine’s instances and collect where burned-in text appears.
- Parameters:
serial_number (str) – The Device Serial Number of the machine, or
""for every series with no Device Serial Number.sample_size (int) – The largest number of instances to read. A machine with more instances is sampled at random.
min_confidence (float) – The lowest OCR confidence, 0 to 100, that a text candidate needs to be kept.
- Returns:
Every text candidate found. Call
to_zones()on it for grouped redaction zones.n_sourcescounts only the sampled instances that were read (at least one frame through OCR). So an instance that could not be read does not dilute a zone’s occurrence rate. Each instance that failed is logged at ERROR, counted in a WARNING, and written as oneWARNINGaudit row that names the instance and the reason. That row grades the runREVIEW_REQUIRED. A worker process runs the caller’stesseract_cmd.- Return type:
- Raises:
RuntimeError –
pixel_analysis.OcrUnavailableErrorif theocrextra is not installed, or if thetesseractbinary does not answer. It is raised before any worker is dispatched and before the graph is read.pixel_analysis.PixelScanError, which carries.failuresand.attempted, if at least one sampled instance failed and none could be read. It is raised after the pass, the audit rows and the warning.
- reconcile_private_tags() int#
Delete stored private-tag rows that the store’s core attributes do not hold.
A repair for a store de-identified before 0.9.1, whose stripped private tags come back when it is opened.
It does three things:
It deletes every
instance_attributesrow whose tag is absent from its instance’s stored core attributes.It removes the same tags from the in-memory graph.
It writes one
RECONCILE_PRIVATEaudit row per affected instance.
The graph edit advances no revision. Afterwards, the store and the graph agree, nothing reads as unsaved, and stored PHI statuses are kept.
Call it only for a store you know was de-identified before 0.9.1. In a store that keeps its private tags (
remove_private_tags: false, saved by 0.9.1 or later), those rows are the private data, and this method deletes all of them. If you are not sure, runanonymize()andsave()instead, because a save removes the rows of tags that the graph no longer holds. Nothing makes this choice automatically.- Returns:
The number of
instance_attributesrows deleted, not tags. A value with multiplicity 3 is three rows, and a tag that holds an empty value is one row. 0 means that nothing changed.- Return type:
int
- export(folder: str, format: str = 'dicom', **options)#
Export the session to a directory in the requested format.
Both built-in formats save the session (
save(sync=True)) before they write, after any refusal listed underRaises:. A refused call saves nothing.Either format writes one
WARNINGaudit row, and changes nothing that it writes, when the instances that it writes carry PHI statuses of one of these kinds:Statuses recorded under a policy that is neither the one in force nor one that this session scanned under.
Statuses with no recorded policy (a store written before 1.0).
The report then grades
REVIEW_REQUIRED.check_burned_in=Truere-audits first, so it never writes this row.Under a
burned_in_textpolicy (#1108), thedicomformat reads each instance’s record of the lastredact()pass, and runs no OCR. It loads each frame once to check that the record names the pixels that the instance holds now. Withcheck_burned_in=True, it reads with the policy’s reader the pixels that it is about to write instead (see_export_dicom). These rules apply to an instance that holds pixels:If it was never checked under the policy’s threshold and zones, or its pixels changed after the read, it is withheld under
redactandwithhold, and written underreport.If text was found in it, it is withheld under
withhold. Underredactit is withheld until a redaction that carries its boxes has landed. Underreportit is written.
Each of these writes one
WARNINGrow, and theEXPORTrow counts the withheld instances apart. An instance with no pixels is neither read nor gated.Either format also writes one
WARNINGaudit row, and logs oneWARNINGline, whenpatient_idsnames an ID that no patient in the session holds. The row and the log line count such IDs by position and never name them, and the report then gradesREVIEW_REQUIRED. The patients that match are exported as asked, and nothing raises. Thedicomformat does the same for asubsetvalue that names nothing in the session at any level.A format served by any exporter other than the two built-in classes (one registered through
exporters.register, a subclass of a built-in, or another class registered asdicom) writes oneWARNINGaudit row before it runs. The row says that its output is not attested by Isocenter, so the report gradesREVIEW_REQUIRED. None of the export gates runs for it, and it writes noEXPORTrow. The registry is provisional until 1.1. SeeExporter registry.- Parameters:
folder (str) – Output directory.
format (str) – Registered format name. “dicom” (default) writes cleaned DICOM files. “wfdb” writes PhysioNet WFDB records.
**options (dict) – Passed through to the selected exporter. The DICOM format’s options are listed under “DICOM export options” on the Session API page.
- Returns:
The selected format’s own result object. The DICOM exporter returns an
ExportSummary. Itswrittencounts the files that reached disk, and itsfailuresnames the instances that did not.writtenis counted over de-duplicated UIDs, because the UID names the output file. Two instances that share one UID are two successful write operations and one file, because the second write overwrote the first. The WFDB exporter returns aList[str]of paths. An empty list means that nothing was attempted, because an export that attempted records and wrote none raises instead.- Return type:
Any
- Raises:
ValueError – If
formatis not a registered export format. Also ondicom, before anything is written, for asubsetquery that does not run, or asubsetDataFrame with none of SOPInstanceUID, SeriesInstanceUID, StudyInstanceUID and PatientID. Also, on both formats, from the save that an export begins with, if an instance with unsaved changes holds a SOP Instance UID that is not astr. The message gives the count, and nothing is saved or written (#721: this was sqlite’sIntegrityError). The same applies if a patient, study or series holds a Patient ID, Study Instance UID or Series Instance UID that is not astr, with a count per level (#949:Nonewas sqlite’sIntegrityError, and for any other type the save returned and the store lost the rows).TypeError – For an option name that the selected exporter does not recognise. Then nothing is written. The two formats do not accept the same options, so a caller that forwards one dict to both must split it. Also, on both formats and before anything is written, for a
patient_idsthat is a barestr(wrap one ID in a list), is bytes-like, is not iterable, or holds an element that is not astr. Also ondicom, for asubsetthat is bytes-like, is not iterable, or holds an element that is not astr.OcrUnavailableError – On
dicomwithcheck_burned_in=Trueunder aburned_in_textpolicy, if a reader that the policy needs cannot run (#1108): tesseract (theocrextra and the binary) underdetector: tesseractor a narrowedtarget, the text detector underdetector: db(TextDetectorUnavailableError), or the names model whentargetnamesnames(NlpUnavailableError). Underdetector: dbwithtarget: any, tesseract is not needed. It is aRuntimeError, raised before the tag scan, the save, any row or any file.ExportError – From either exporter, if zero of N attempted instances are reported written and at least one failed. The folder then holds none of them, with one exception (#1020). If every planned instance was written under file names that the volume resolved to one file, and that file could not be read back as any of them, the folder holds that one file, and the
ERRORrow keyedMULTIPLEsays so. An empty plan (zero of zero) does not raise, because a subset that matched nothing is a fact about the run, and theEXPORTaudit row already carries it. A DICOM export whose every instance the pre-export scan withheld does not raise either. Nothing was attempted, and itsWARNINGrows grade the run.
- export_dataframe(output_path: str, expand_metadata: bool = False, patient_ids: List[str] | None = None)#
Write the cohort report to CSV or Parquet, and return it.
The format is chosen from the extension:
.parquetwrites Parquet, anything else writes CSV.output_pathis required and has no default (#812). The file can hold the source identifiers (it does beforeanonymize()), so the caller must name where it lands. Useget_cohort_report()for the frame alone, with no file.It reports the session’s in-memory graph and does not
save()first, so pending edits are not committed as a side effect.Parquet holds a column of sequences (a multi-valued tag such as Image Type) as a list column when its values are uniform. Uniform means that every non-null cell is a sequence whose non-null elements are all of one scalar family. A column that is neither that nor scalars of one family is written as text, each value as the CSV writes it. Examples of such a column are a tag single-valued in one file and multi-valued in another, or a
strbeside anint. Missing values stay null in both formats. Other columns are written as they are.- Parameters:
output_path (str) – The output file path (ends with .csv or .parquet). Required. Its directory is created if missing.
expand_metadata (bool) – If True, includes all DICOM attributes as columns.
patient_ids (Iterable[str], optional) – Restrict the export to these Patient IDs. They are read by
get_cohort_report(), which this method calls.Nonemeans every patient in the session, and an ID that no patient holds is counted in aWARNINGlog line.
- Returns:
The frame as built, before any Parquet conversion. It is the same frame for either format.
- Return type:
pd.DataFrame
- Raises:
ImportError – If pandas (or, for Parquet, a Parquet engine) is not installed.
TypeError – For a
patient_idsthatget_cohort_report()refuses (a barestr, bytes-like, not iterable, or a non-strelement). It is raised before the directory is created or any file is written.Exception – Whatever the Parquet write raised, after it is logged.
- get_cohort_report(expand_metadata: bool = False, patient_ids: List[str] | None = None) pd.DataFrame#
Return a pandas DataFrame of the cohort, one row per instance.
- Parameters:
expand_metadata (bool) – If True, add a column for every DICOM attribute.
patient_ids (Iterable[str], optional) – Restrict the report to these Patient IDs, read exactly as
export()reads itspatient_ids.Nonemeans every patient in the session. An empty iterable matches nobody, because it is a filter that selected nothing, not an absent filter. An iterator is read once. An ID that no patient holds selects nothing, and oneWARNINGlog line counts it but never names it. A report is a read, so it writes no audit row. A subject whose files carried no Patient ID is selected by the key that this report’sPatientIDcolumn shows for it, not by"".
- Returns:
One row per instance.
- Return type:
pd.DataFrame
- Raises:
TypeError – If
patient_idsis a barestr(wrap one ID in a list), is bytes-like, is not iterable, or holds an element that is not astr. The message names such an element by its position and type, never by its value.
- phi_status_summary() Dict[str, Counter]#
What the session currently knows about the PHI in each entity.
It counts
PhiStatusper level, as each entity stands now, not as the last scan left it. So an entity edited since it was scanned counts as UNSCANNED.Series are not counted, because the scan records a status on patients, studies and instances only.
redact()is the one edit that keeps an instance’s status. An instance that was REMEDIATED, CLEARED or IDENTIFIED before the pass reads the same after it, provided nothing but redaction’s own writes changed it. SeePhiStatus.A status is counted whatever policy it was recorded under.
phi_status_policynames that policy. Anexport()of statuses recorded under a policy other than the one in force says so.- Returns:
Keyed “patients”, “studies”, “instances”. Each value is a Counter of PhiStatus to how many entities carry it.
- Return type:
Dict[str, Counter]
- generate_report(output_path: str, format: str = 'markdown') None#
Write the compliance report for the session’s store.
The report holds the grade (
PASSorREVIEW_REQUIRED). The grade is decided from the audit trail that the store holds and the graph’s PHI statuses (“How the grade is decided” in Analytics & Reporting). The report also holds the session’s counts, the audit actions, data loss, exceptions, and the policy in force. Generate it afterexport(), because an export writes rows of its own. A report generated before any export carries a note that says so.- Parameters:
output_path (str) – The file path where the report should be saved.
format (str) –
'markdown', the one spelling accepted. Defaults to'markdown'.
- Raises:
ValueError – For any other
format,'md'and case variants included. In that case, no file is written.
- generate_manifest(output_path: str, format: str = 'html') None#
Write an HTML or JSON manifest of every instance in the session.
It has one entry per SOP Instance in the session, with its source file path and key metadata (Modality, Manufacturer, and so on).
Each JSON item’s
anonymizedis True when both of these are true:The last tag-policy PHI scan left no identifier unremediated on that instance’s patient, study or instance.
None of the three has been edited since.
It does not mean “
anonymize()ran” (a clean input reads True afteraudit()alone), and it says nothing about burned-in pixel text.After
anonymize(), the UIDs listed are the replacements, beside each instance’s source file path. So the manifest maps source files to exported UIDs. Keep it with the store, not with an export.- Parameters:
output_path (str) – The file path where the manifest should be saved.
format (str) –
'html'or'json', exactly. Defaults to'html'.
- Raises:
ValueError – For any other
format, a case variant included. In that case, no file is written.
- save_analysis(report)#
Saves the results of a PHI analysis to the store.
- Parameters:
report (Union[PhiReport, List[PhiFinding]]) – The PHI report object or list of findings to save.
- compact()#
Rewrite the pixel sidecar (
_pixels.bin) to reclaim the space of frames no instance references, and point every loader at the new offsets.This is an expensive I/O operation. It starts with
save(sync=True), so it waits for a background save that is running.Two behaviours are contract, observable from any thread of this session:
It raises
RuntimeErrorwhile aredact()oringest()pass is open on the same store. The check comes first, before the leading save, so a refused call has done nothing.A
redact()oringest()that starts while it is saving or rewriting waits, bounded by 180 s, and then proceeds.
Every frame writer, and this method for the whole rewrite, holds a cross-process lock beside the sidecar, so a frame written while compaction runs lands in the compacted file. A writer that cannot take the lock within 180 s raises
RuntimeError. A background save that expires this way is logged asBackground save failed, and its instances stay unsaved for the next save.The rewrite holds the lock for its whole length, about 0.2 s per GB on local SSD. A
close()whose persistence worker is queued behind a compaction longer than 30 s reports that worker as wedged.- Raises:
RuntimeError – In three cases: while a
redact()oringest()pass is open on this store, when a save is still queued on the persistence manager after the leading save, or when the sidecar lock cannot be taken within 180 s.
- release_memory()#
Release cached pixel and waveform data from every instance.
Each instance goes through
Instance.unload_pixel_data(), with its precondition. So an array replaced throughset_pixel_data()and not since written is kept. An array changed in place is not tracked, so it is dropped here, and the nextget_pixel_data()returns the frame from before the change. Only an array that a save has already written can be changed in place, because a frame read from a file or from the store is read-only.Cached waveform samples are int16 of shape (num_samples, num_channels): about 80 KB for a 10-second 12-lead, about 104 MB for a 24-hour 3-channel Holter.
Its progress bar follows
ISOCENTER_SHOW_PROGRESS.
- close()#
Shut the session down: the persistence-manager thread, the audit thread that owns the sqlite connection, and the process pool. A session that is never closed leaks its worker subprocesses for the life of the process. If the pool is broken because one of its workers ended outright, a worker of the pool that is still running 10 s after
close()finds the pool broken is sentSIGKILL, and oneWARNINGline names that worker.All three steps run even if an earlier one raises. If more than one fails, the first failure is raised and the later ones are logged. A second call is safe. It repeats the shutdown messages and the unsaved-instances WARNING.
DICOM export options#
export(folder, format="dicom", **options) takes the options below for
the dicom format. Their names and defaults are frozen with export()
(API stability). An option name the format
does not take raises TypeError, and export() writes nothing. The
table comes from the format’s own method, which is private. Pass the
options to export(), and never call that method directly.
- DicomSession._export_dicom(folder: str, use_compression=True, check_burned_in=False, check_reversibility=True, patient_ids: List[str] = None, show_progress=True, subset=None, verify_readback=False)#
Export the session as DICOM, one folder per patient, study and series.
- Parameters:
folder (str) – The output directory path.
use_compression (bool) – If True, compresses output images with JPEG 2000 (lossless). A 16-bit image with more than one sample is also written this way, and pydicom with only its Pillow plugin cannot decode it. The export names each such instance at INFO. An image of 32- or 64-bit integer samples, which JPEG 2000 here cannot carry exactly, is written uncompressed instead, and is also named at INFO (#771).
check_burned_in (bool) – If True, scans for PHI before exporting, and withholds every instance that still carries an identifier at any level of its hierarchy. The scan is an
audit(), run before the export’s own save. So it raises whataudit()raises, including a failed backgroundsave()that still fails (#941), and nothing is written to the folder. Each withheld instance writes oneWARNINGaudit row. The row names the instance and the level (patient, study, series or instance) that carried the identifier, but never the value. So the report gradesREVIEW_REQUIREDand lists these instances in section 4. Withheld instances count as requested and not written (“1 of 2 requested”), and theEXPORTrow says how many were withheld. An export that withheld everything returns an empty summary and does not raise, because nothing failed. An instance outsidesubsetis not withheld, because it was never asked for. Under aburned_in_textpolicy (#1108), the export also reads with the policy’s reader (OCR by tesseract, or the text detector underdetector: db) every planned instance that holds pixels, as it is about to be written, after the configured zones. That read, not the record of the lastredact(), decides the instance. An instance with text found is withheld underredactandwithhold, and written underreport. An instance with nothing found is written. An instance whose read failed is withheld underredactandwithhold, and written underreport. Each of these writes oneWARNINGrow that names the instance, the count and the frames, but never the text. The read changes nothing in the session. It redacts no pixel and moves no UID. If a reader that the policy needs cannot run, it raisesOcrUnavailableErrorbefore the scan, the save and any row. Tesseract (theocrextra and the binary) is needed underdetector: tesseractor a narrowedtarget, the text detector underdetector: db(TextDetectorUnavailableError), and the names model whentargetnamesnames(NlpUnavailableError). Underdetector: dbwithtarget: any, tesseract is not needed.check_reversibility (bool) – If True (the default), warn when the files that this export wrote still carry the encrypted originals that
lock_identities()embeds, and record the disclosure in the audit log. The check runs after the write, against what reached disk. Anyone who holds the key can recover those identities, and a recipient of the cohort cannot see this for themselves. Passing False silences the warning and skips the audit row. The export itself is the same either way, because this check reports and does not withhold.patient_ids (Iterable[str], optional) – Limit export to specific Patient IDs. Only
None, or the parameter omitted, means every patient. An empty list, tuple or set is a filter that selected nobody, and nothing is written. An iterator is read once before the walk. A barestr(wrap one ID in a list), a bytes-like value, a non-iterable, or an element that is not astris refused withTypeErrorbefore anything is flushed or written. An ID that no patient in the session holds selects nothing. It is counted but never named, in oneWARNINGlog line and oneWARNINGaudit row, so the report gradesREVIEW_REQUIRED. The patients that do match are exported as asked. Afteranonymize(), a patient is selected by its replacement ID. Thewfdbformat andget_cohort_report()readpatient_idsin the same way.show_progress (bool) – If True, shows progress bar.
subset (Union[str, pd.DataFrame, Iterable[str]]) –
Filter the export with one of these:
A pandas query string, run against
get_cohort_report(expand_metadata=True).A DataFrame. It is read by the first of SOPInstanceUID, SeriesInstanceUID, StudyInstanceUID and PatientID that it carries. One with none of them raises
ValueError.Any other iterable of UIDs at any level (list, tuple, set, a generator), read as
patient_idsis.
Only
Nonemeans no filter, and an empty one selects nothing. A bytes-like value, a non-iterable, or an element that is not astrraisesTypeErrorbefore anything is scanned, flushed or written. A value that names nothing in the session at any level (as itself, as the UID that this store replaced it with, or, for a SOP Instance UID taken beforeredact(), as the instance’s redacted UID) is counted by position and never named, in oneWARNINGlog line and oneWARNINGaudit row, so the report gradesREVIEW_REQUIRED. The rest is exported as asked. A query cannot name anything that the session lacks, so it is never counted.verify_readback (bool) –
If True, each worker reads again the file that it just wrote, before the file is published under its real name. The worker compares the file with what it meant to write, in this order:
Rows, Columns, SamplesPerPixel, NumberOfFrames and BitsAllocated, against the dataset that it serialized.
The file’s
PhotometricInterpretation, against the transfer syntax that the file itself carries. The syntax must admit it, and it must be a single value.Every pixel sample, decoded the way
ingest()decodes it and compared bit for bit with the samples written, after redaction.A DICOM waveform’s
WaveformDatabytes.
The stored samples are compared, not a colour conversion of them. A file labelled
YBR_FULLorYBR_FULL_422over samples that are not unsigned 8-bit is also decoded with pydicom’s colour conversion, asingest()decodes it. It fails when that decode raises, which it does for 16-bit and int8 samples. A value outside the declared BitsStored fails an uncompressed file, because every conformant reader masks it (-3024 at BitsStored 12 reads as 1072).Passing True can cost a file that the default export delivers. By default, a Photometric Interpretation that the written syntax does not admit (
YBR_ICTorYBR_RCTon an uncompressed file,YBR_PARTIAL_422/_420on any file that this exporter writes) is written exactly as the instance declared it, with aWARNINGaudit row and aREVIEW_REQUIREDgrade. With True, that instance fails, gets anERRORrow, and no file for it reaches the output folder. The reason names the label, the syntax and a remedy. The check does not ask whether the samples are really in the colour space that the label names.RGBover YBR samples passes, and so does a file under a transfer syntax that the check has no row for.An unreadable or undecodable file, or any mismatch, fails that instance’s export. The instance is counted out of “Instances Written”, gets an
ERRORaudit row, and takes the grade toREVIEW_REQUIRED. When every instance fails, the call raisesExportError. This option is off by default because it costs a second parse and a full decode per instance. That is about twice the time of a default (JPEG 2000) export, and little more for an uncompressed one. Each worker holds one more decoded array while it checks.
- Returns:
What reached disk and what did not. It is empty when nothing was attempted.
- Return type:
- Raises:
TypeError – If
patient_idsorsubsetis of a type that the selection does not take. It is raised before anything is flushed or written.ValueError – If
subsetis a DataFrame that carries none of SOPInstanceUID, SeriesInstanceUID, StudyInstanceUID and PatientID, or a query string that does not run against the cohort report. Also ifconfiguration.burned_in_textis a policy that the loader would refuse in a file (#1108). It is raised before the pre-export scan and the save.OcrUnavailableError – If
check_burned_in=Trueunder aburned_in_textpolicy, and a reader that the policy needs cannot run (#1108): tesseract (theocrextra and the binary) underdetector: tesseractor a narrowedtarget, the text detector underdetector: db(TextDetectorUnavailableError), or the names model whentargetnamesnames(NlpUnavailableError). Underdetector: dbwithtarget: any, tesseract is not needed. It is aRuntimeError, raised before the tag scan, the save, any row or any file.ExportError – If every planned instance failed (nothing written and at least one failure). It is raised last, after the audit rows and the
EXPORTrow are written. A partial export and an empty plan return a summary instead.