Entities API#
The object graph session.store holds: session.store.patients is a
list of Patient, and each holds Study → Series → Instance.
attributes on every entity is keyed by lowercase "gggg,eeee" tag
strings, not keywords. This page renders the names of
isocenter.entities that API stability places in tier 1
or tier 2.
Frozen (tier 1)#
The entity classes as reached from session.store, and the key a subject
with no Patient ID is held under, with its test. A class in this section
does not make every method rendered under it tier 1. The frozen methods
are Instance.get_pixel_data(), set_pixel_data(), unload_pixel_data(),
discard_pixel_data(), get_waveform_data() and set_attr(). The other
methods shown, such as Instance.regenerate_uid() and the sequence
methods, are tier 2. So are pixel_array and waveform_array in
Instance’s attribute table.
What set_attr() stores. It stores the value it is given, with one
exception. It stores a numpy bool, integer or float (a scalar or a 0-d
array) as the Python number it equals. It stores a list or tuple
that directly holds a numpy value as a new list, with each numpy
number in it replaced in the same way. So set_attr("0018,1150", np.int64(7)) leaves the int 7 in attributes, and
set_attr("0018,1150", (np.int64(7),)) leaves the list [7]. A live
export writes what a reopened session writes. An array of one or more
dimensions is not converted. Pass .tolist() or .tobytes() instead. No other numpy value is converted
either. A datetime64, a timedelta64, a complex number and a masked
value stay as given, and the save refuses them.
The entity does not see a value written straight into attributes
(call mark_modified()). A numpy number written that way is converted
when it is saved. export() writes such a number as the Python number
it equals, whether or not it was saved. So the file is the same before
and after a save and a reopen. export() also writes a tuple as the
list it equals, and a finite Decimal that a float can hold as the
float it equals. Under a standard element whose VR is AT, there is
one exception. export() writes a tuple of exactly two integers, or
of exactly two str, as one tag, as pydicom reads it (#1009). The pair
must still be a tuple when the export reads it. After set_attr(), a
tuple that holds a numpy number is a list (above), and a list of
two integers is two tags. A store that was saved and opened again also
holds the pair as a list
(#1016, open). The
save refuses a Decimal, and only a value written straight into
attributes, or a graph built by hand, can hold one. export() changes
none of the three in attributes.
A number under a standard element whose VR holds text
(set_attr("0008,1090", 7)) is not written. The file is exported
without that element, under one DATA_LOSS row that names the tag, the
type and the VR. Pass the text instead. The store holds None, str,
bytes, bool, int, float, pydicom’s DS and IS values, and lists
of those. set_attr() does not raise for a value of another type. The
next save(sync=True), export() or compact() raises TypeError
that names the instance, the tag and the type
(API stability, Exceptions). Instance.set_attr() can
raise ValueError for an edit to a pixel descriptor, which is a
different check (API stability).
What assigning Instance.sop_instance_uid does. It moves the field
and the (0008,0018) element together, and marks the instance edited.
For example, instance.sop_instance_uid = "1.2.3.4" leaves "1.2.3.4"
in instance.attributes["0008,0018"], and the export writes the file as
1.2.3.4.dcm with that UID inside. The export does not write an
instance assigned ''. Its file-name rule refuses a UID that cannot
name a file, and reports the instance as a failure keyed UNKNOWN.
Assigning the value that the field already holds changes nothing.
series.series_instance_uid, study.study_instance_uid and
patient.patient_id need no such step. The export stamps each file’s
copy from the owner.
The in-memory DICOM object graph.
Patient, Study, Series and Instance, the DicomItem and
DicomSequence nesting beneath an instance, Equipment, and the
persistence (TrackedEntity) and PHI-status (PhiStatus, ScanPolicy)
bookkeeping every graph entity carries.
- NO_PATIENT_ID_PREFIX = '\\no-patient-id\\'#
The prefix of the
patient_idthat ingest gives a subject whose files carry no usable Patient ID:NO_PATIENT_ID_PREFIX + <StudyInstanceUID>.The backslash is the point. It is DICOM’s value delimiter, so pydicom reads a Patient ID that holds one as a
MultiValue, and ingest refuses a multi-valued Patient ID. So no single-valued Patient ID read from a file can equal a key built on this prefix. No placeholder string (UnknownPatient,'') could promise that, because a real Patient IDUnknownPatientcan exist, and it would merge with every ID-less file.The key is not
ANON_-shaped, so_is_replacement_idandcanonical_patient_keytreat it as an original. Its date offset is the pseudonym it would be replaced by, under the project secret, and the key is never replaced. The key never leaves the store, because every writer readsexported_patient_id. It embeds the source Study Instance UID, and it stays anchored there whatever a later UID replacement does to the study.is_synthetic_patient_idis the only test for it. Do not spell the prefix anywhere else.
- is_synthetic_patient_id(value) bool#
Whether
valueis the key ingest gave a subject with no Patient ID.- Parameters:
value (Any) – A
patient_id.- Returns:
True for a string that starts with
NO_PATIENT_ID_PREFIX.- Return type:
bool
NO_PATIENT_ID_PREFIX is the start of the key a subject whose files
carry no Patient ID is held under. The key never reaches an exported
file.
- Patient(patient_id: str, patient_name: str, studies: List[Study] = list())#
Root of the object hierarchy. Groups Studies by Patient ID.
Attributes:
Name
Type
Description
patient_idstr
The primary patient identifier.
patient_namestr
The patient’s name.
studiesList[Study]
List of studies belonging to this patient.
- Study(study_instance_uid: str, study_date: Any, series: List[Series] = list(), date_shifted: bool = False, study_time: str | None = None)#
Groups Series by Study Instance UID. Represents a single patient visit or examination.
Attributes:
Name
Type
Description
study_instance_uidstr
The unique identifier for the study.
study_dateAny
The date of the study.
seriesList[Series]
List of series belonging to this study.
date_shiftedbool
Whether dates in this study have been shifted.
date_shift_vouches_foranswers whether this study date is one that the shift produced.study_timeOptional[str]
A time of the study that a caller may hold here. Ingest never sets it. The store has no column for it (it reads None after a reopen). No export writes it: each file carries its own instance’s Study Time
(0008,0030)(#953), as it carries its own Series Number and Modality.
- Series(series_instance_uid: str, modality: str, series_number: int, equipment: Equipment | None = None, instances: List[Instance] = list())#
Groups Instances by Series Instance UID. Typically represents a single scan or reconstruction.
Attributes:
Name
Type
Description
series_instance_uidstr
The unique identifier for the series.
modalitystr
The source’s Modality as ingested (e.g., ‘CT’, ‘MR’). The export writes each instance’s own
0008,0060, after the configuration’s rules, not this value (#869).series_numberint
The source’s Series Number as ingested. The export writes each instance’s own
0020,0011, after the configuration’s rules, not this value. The folder and WFDB record names read the same instance attribute (#869). An assignment to it changes no file and does not mark the instances edited.equipmentOptional[Equipment]
The equipment used for this series.
instancesList[Instance]
List of instances belonging to this series.
- Instance(sop_instance_uid: str = '', sop_class_uid: str = '', instance_number: int = 0, file_path: str | None = None, source_path: str | None = None, pixel_array: ndarray | None = None, waveform_array: ndarray | None = None)#
One DICOM file’s worth of data (an SOP Instance), with its pixels loaded on demand.
attributes,sequencesandattribute_vrscome fromDicomItem.Attributes:
Name
Type
Description
sop_instance_uidstr
SOP Instance UID (0008,0018).
anonymize()andredact()can replace it.sop_class_uidstr
SOP Class UID (0008,0016).
instance_numberint
Instance Number (0020,0013). It is not unique within a series. It is 0 for an ingested file that has none, and
0020,0013is then absent fromattributes(#870).file_pathOptional[str]
A file whose pixels match this instance now. It is read when the store holds no frame for the instance. It is None after redaction.
source_pathOptional[str]
The file this instance was read from. Redaction does not change it.
pixel_arrayOptional[np.ndarray]
The pixels while resident, else None. Read them with
get_pixel_data().waveform_arrayOptional[np.ndarray]
The waveform samples while resident, else None. Read them with
get_waveform_data().- regenerate_uid(new_uid: str)#
Gives this instance the SOP Instance UID its redacted pixels take.
Call this whenever the pixel data changes, so that the changed image is never mistaken for the original.
new_uidis required. The redaction pass derives it from the source SOP Instance UID, the redaction’s zones and the project secret. So the same redaction gives the same UID, and no worker process holds the secret.This method does three things:
It sets the property and the
0008,0018element together.The first time the instance’s UID moves, it records the UID that the instance held before in
SOURCE_SOP_UID_ATTR.It detaches the instance from its source file (
file_path = None), because the instance no longer matches that file’s pixels.
- Parameters:
new_uid (str) – The derived SOP Instance UID.
- set_attr(tag: str, value: Any)#
Sets an attribute, and keeps resident pixels reading as it declares.
Every tag is written as
DicomItem.set_attrwrites it. Some descriptors control how a frame is read: Rows, Columns, SamplesPerPixel, NumberOfFrames, BitsAllocated and PixelRepresentation. An edit to one of them while pixels are resident also settles the resident array. This is because a save writes the array’s bytes, and every later read takes those bytes under the edit. The declaration wins:An edit under which the bytes read as they read now (the same dtype and shape) is a plain write.
An array that a save wrote is released after the write. The next read then rebuilds it under the edit: from the store, or from the source file for an instance read from its source file. Its bytes are stored, so nothing is lost. A memory-only array has nowhere to be reloaded from, so it stays, as
unload_pixel_datarefuses to drop it.An array set through
set_pixel_data()and not yet written is published again as the edit reads its bytes. That is a view under the new dtype, in the new shape, published together with the write, so no read sees the new declaration beside the old array. The array stays unwritten, anddiscard_pixel_data()still restores what the set replaced.
Each edit is judged alone. Suppose that you change a geometry in two steps, and the bytes fit the end state (BitsAllocated 8, then Columns 8, over a 4x4 uint16 set). Then the first step is refused. Instead, set the array that you mean, which writes its own descriptors.
A read in flight when the edit lands is not published under the old declaration. It reads again under the new descriptors.
- Parameters:
tag (str) – The DICOM tag string. Case-insensitive.
value (Any) – The value to set.
- Raises:
ValueError – If all of these are true: the edit is to a described tag, the resident array was set through
set_pixel_data()and not written since, and the edit reads its bytes as a different number of bytes or does not parse as an integer. The message reads, for example: “BitsAllocated would read the unsaved uint16 (4, 4) array set by set_pixel_data() as 16 1-byte uint8 samples, 16 bytes, and the array holds 32. Pass the array you mean to set_pixel_data(), which writes its own descriptors.” The value is never in the message. It is raised before anything is written, so the attribute and the revision are unchanged.
- unload_pixel_data() bool#
Frees the cached pixel_array, but only when it can be brought back.
Two things must both be true:
There is somewhere to reload from (the source file, or the store’s sidecar).
The resident array was not replaced through
set_pixel_data()since it was last written.
Otherwise the array is the only copy of those pixels, and it is kept.
An array changed in place is not detected. Only a writeable array can be changed in place, and a frame read from a file or from the store is read-only (an assignment into it raises). The case that can occur is a replacement that a save has since written. That array is writeable, so
arr = inst.get_pixel_data(); arr[...] = 0on it diverges from the stored frame, and an unload then drops the change.Use
discard_pixel_data()when you mean to drop unsaved pixels.- Returns:
True if unloaded (or already absent), False if it was unsafe to unload: either the data is in memory only and nothing could bring it back, or it has diverged from what is stored.
- Return type:
bool
- discard_pixel_data() bool#
Frees the cached pixel_array even if it has unwritten changes.
Use it to throw the resident array away, so that the next
get_pixel_data()reloads the stored frame, read under the instance’s current descriptors.It undoes the whole
set_pixel_data()it discards. The pixels go back to what they were before the first unwritten replacement. So does every descriptor that call wrote (Rows, Columns, SamplesPerPixel, NumberOfFrames, PhotometricInterpretation, PlanarConfiguration, BitsAllocated, PixelRepresentation and the float/bool dtype carrier), absent ones included. A pixel descriptor edited between the set and the discard goes back with them, because while the replacement is resident, that edit describes the replacement. So the next read is the stored frame as it was stored.Once the replacement is written (by a save or by redaction), it is the stored frame, and there is nothing to undo. The array is dropped, and the descriptors, which describe it, stay. A refusal (below) keeps both the array and the descriptors that describe it. A discard of an unwritten replacement leaves the instance dirty, as the set did.
unload_pixel_data()answers “free this if it is safe”. This method answers “throw this away”.- Returns:
True if discarded (or already absent), False if there is nowhere to reload from at all.
- Return type:
bool
- get_pixel_data() ndarray | None#
Returns pixel_array, loading it if it is not in memory.
In order, it:
Returns the cached
pixel_array.Loads the frame from the store’s sidecar, if it holds one.
Reads
file_pathwith the decode thatingest()uses: pydicom, then imagecodecs where pydicom has no plugin. A file that ingest refuses is refused here, in the same words. The decoded samples are read under the instance’s pixel descriptors where the instance holds them, as the sidecar’s samples are. The file supplies the samples and any descriptor that the instance lacks.
A read whose decoder returns RGB from a YBR-labelled file says so. These sources come back converted to RGB:
an 8-bit
YBR_FULLJPEG-LS file read through the imagecodecs fallback, asingest()stores ita JPEG 2000
YBR_RCT/YBR_ICTfile, whose codec undoes the colour transformany 8-bit YBR source that pydicom decodes, which pydicom returns as RGB by default
An instance that carries a PhotometricInterpretation is then relabelled
RGBto match, and that advances its revision. This is the one write that a read makes, and it is made only when the decode converted.- Returns:
The pixel data as a numpy array, or None when the instance carries no pixel element. From a file, the dataset alone decides that. The result is None when the file was read and holds none of Pixel Data (7FE0,0010), Float Pixel Data (7FE0,0008) and Double Float Pixel Data (7FE0,0009), whatever its transfer syntax. It is never None because of what a failure’s message says. A frame that could not be decoded is not None: it raises. A file with no pixel element whose pixels are elsewhere also raises, when pydicom has no decoder for its transfer syntax. Such a file holds Pixel Data Provider URL (0028,7FE0) at the top level, or is under a JPIP Referenced syntax.
- Return type:
Optional[np.ndarray]
- Raises:
RuntimeError – If loading fails because of transfer syntax issues, missing codecs, or a pixel element that the reader could not decode. Also from a file, when an encapsulated pixel element’s offset table names a different number of frames from NumberOfFrames:
Lazy load failed for instance <uid>: RuntimeError: <table> names N frames; NumberOfFrames declares M. The message names the instance, never the source file. Also from a file that ingest would refuse, in ingest’s words. Such a file has a header that pydicom’s validation rejects, whether or not pydicom has a plugin for its syntax (Missing required element: (0028,0101) 'Bits Stored'), or a 16-bit YBR_FULL frame. Also from the sidecar, when a descriptor written since the frame was stored asks for a reading that the stored bytes cannot satisfy (BitsAllocated 16 -> 8, or Rows x Columns smaller than the stored samples):Pixel Loader failed for <uid>: Integrity Error: .... A reopened session gives the same refusal. A file gives the same refusal for the same edit, asLazy load failed for instance <uid>: RuntimeError: Integrity Error: frame for <uid> holds N samples; geometry (R, C) needs M (one trailing pad byte is tolerated, nothing else).FileNotFoundError – If the file path does not exist.
- unload_waveform_data() bool#
Clear cached waveform samples to free memory.
It unloads only when the store holds the samples to read them back from. Unlike for
unload_pixel_data, a source file alone is not enough.- Returns:
True if unloaded (or already absent). False if unsafe, that is, if the samples are in memory only and nothing could reload them.
- Return type:
bool
- get_waveform_bytes() bytes | None#
Return the original Waveform Data (5400,1010) bytes, undecoded.
The DICOM export writes these back verbatim, so a DICOM to DICOM round trip is byte-exact. They are not cached, so an instance does not hold both the bytes and the decoded array.
- Returns:
Raw sample bytes, or None when this instance has no waveform or its samples are not backed by the sidecar.
- Return type:
Optional[bytes]
- get_waveform_data() ndarray | None#
Return decoded waveform samples, loading from the sidecar if needed.
- Returns:
int16 array of shape (num_samples, num_channels), or None if this instance has no waveform.
- Return type:
Optional[np.ndarray]
- set_pixel_data(array: ndarray)#
Sets the pixel array and updates the descriptors that describe it.
The instance’s own attributes decide what each axis of the array means, not the array’s shape, because
(frames, rows, cols)and(rows, cols, samples)are the same rank. The array decides how large each axis is.It updates these tags, each only when the value actually changes:
Rows (0028,0010)
Columns (0028,0011)
SamplesPerPixel (0028,0002)
NumberOfFrames (0028,0008), if > 1 or already declared
PhotometricInterpretation (0028,0004), only to correct an outright contradiction – YBR_FULL and MONOCHROME1 survive
PlanarConfiguration (0028,0006), only when colour and undeclared
BitsAllocated (0028,0100), from the array’s itemsize
PixelRepresentation (0028,0103), from the array’s dtype kind: 1 for signed integers, 0 for unsigned and bool. Left alone for a float array, because PS3.5 Section 8.2 forbids it beside a float pixel element and the export deletes it there.
A genuinely ambiguous shape is accepted with a WARNING, so a hand-built graph can take pixels before its attributes (for
DicomExporter.write_tree()). The export worker refuses the same geometry.The prior value, or absence, of each descriptor that it can write is recorded once, at the first replacement since the array was last written. A later set keeps that first record. The record is kept until the array is written (by a save or by redaction), or until
discard_pixel_data()puts it back. Until the array is written,unload_pixel_data()refuses to drop it.- Parameters:
array (np.ndarray) – The pixel data to set. It can be 1D, 2D, 3D, or 4D.
- Raises:
ValueError – If the sidecar cannot round-trip
array.dtype. The accepted set is unsigned and signed integers of 1, 2, 4 or 8 bytes,bool, andfloat16/float32/float64.complex64,object, strings, structured and void dtypes, datetimes andfloat128are refused. Byte order is normalised, not refused, so a big-endian array is accepted and stored native-order. This check runs before any change, so a caughtValueErrorleaves the instance exactly as it was.ValueError – If the instance declares a SamplesPerPixel that no axis of
arraycan carry, or if the rank is unsupported. This one raises afterpixel_arrayhas been assigned.
- DicomItem#
Base class for any entity that holds DICOM attributes and sequences.
This class gives a dictionary-like interface to manage DICOM attributes. Persistence state comes from TrackedEntity. Items nested in sequences are not stored separately, so the subtree form below reaches them.
Attributes:
Name
Type
Description
attributesDict[str, Any]
A dictionary mapping generic DICOM tags to values.
sequencesDict[str, DicomSequence]
A dictionary mapping tags to nested DicomSequences.
attribute_vrsDict[str, str]
The source Value Representation of private tags, where one was known.
- set_attr(tag: str, value: Any)#
Sets a generic attribute by its hex tag (e.g., ‘0010,0010’).
The tag is lowercased first, so
0008,103Eand0008,103ename one attribute. Ingested keys are always lowercase, and a key in another casing would read as absent rather than raise.The value is stored as the object given, except that a numpy bool, integer or float becomes the Python number it equals (
np.int64(7)becomes 7). Alistortuplethat directly holds any numpy value,np.str_included, becomes a new list in which each numpy number is converted. So a live export writes what a reopened session writes. An array of one or more dimensions is not converted: pass a list or bytes.Nothing is refused here. The store holds
None,str,bytes,bool,int,float, pydicom’s DS and IS values, and lists of those. For any other value, the nextsave(sync=True),export()orcompact()raises aTypeErrorthat names the instance, the tag and the type.- Parameters:
tag (str) – The DICOM tag string. Case-insensitive.
value (Any) – The value to set.
- add_sequence(tag: str) DicomSequence#
The sequence at
tag, created empty if it is not there yet.A sequence with no items is kept as one. Ingest and hydration call this before they add items, so a zero-item
SQsurvives both.It calls
mark_modified()only when it creates the sequence. A call on a tag that already has one changes nothing that the store must hold.- Parameters:
tag (str) – The DICOM tag for the sequence. Case-insensitive.
- Returns:
the sequence now at
tag, existing or new.- Return type:
- Equipment(manufacturer: str, model_name: str, device_serial_number: str = '')#
Immutable Equipment definition. It is frozen, so it can be hashed, and sets of unique equipment can be built from it.
Attributes:
Name
Type
Description
manufacturerstr
The manufacturer of the equipment.
model_namestr
The model name of the equipment.
device_serial_numberstr
The serial number (optional).
- classmethod from_parts(manufacturer, model_name, device_serial_number) Equipment | None#
Builds an
Equipmentfrom a file’s or a row’s three fields, or nothing.A series has equipment if and only if it has a manufacturer, a model name or a Device Serial Number. A serial alone is equipment (review of #1111, owner ruling of 2026-10-14). Every
serial_numberrule matches on the serial. A series that held a serial but no equipment was reached by no exact rule, and was reached byserial_number: ""although it had a serial. A store saved before that ruling held such a series with no equipment and wrote""for its serial. So that series reloads as a series with no serial.The arguments are positional, in field order, and all three are required. No normalisation:
NonestaysNone, sofrom_parts("ACME", None, None)equalsEquipment("ACME", None, None).- Parameters:
manufacturer (Optional[str]) – Manufacturer (0008,0070).
model_name (Optional[str]) – Manufacturer’s Model Name (0008,1090).
device_serial_number (Optional[str]) – Device Serial Number (0018,1000).
- Returns:
the equipment, or
Nonewhen none of the three is present.- Return type:
Optional[Equipment]
Documented but internal (tier 2)#
These names are safe to call. They may change in a minor 1.x release,
never in a patch release. The minor release says so in a Breaking
CHANGELOG entry that names the old spelling and the new one
(API stability).
- TrackedEntity#
Tracks whether an entity holds changes the session store does not have.
This is persistence bookkeeping and nothing else. It says whether the object in memory has been written to the session store. It does not say whether the object still carries identifiers, which is a separate question with its own vocabulary (
phi_status).Read the state through
has_unsaved_changes, and move it throughmark_modified()andmark_persisted(). There is no setter: an entity can be told what happened to it, but not told what it is.- property has_unsaved_changes: bool#
Whether this entity holds changes the store does not have.
- mark_modified()#
Records that this entity changed and needs writing again.
- mark_persisted(revision: int | None = None)#
Records that a revision of this entity reached the store.
Never moves backwards: a revision older than one already recorded changes nothing.
- Parameters:
revision (int, optional) – The revision that was written. Defaults to the current one, which is only correct when nothing can have changed since the write. A save that takes time should capture the revision before it starts and pass that here.
- property phi_status: PhiStatus#
What the last scan concluded, if it still applies.
It reads UNSCANNED once the entity has changed since the scan ran, because no status can describe content that the entity no longer holds. A status is recorded under a policy, which
phi_status_policynames. This property reads the status as recorded and never consults the policy in force. A nestedDicomItemtakes a status from remediation only (audit()records none on it), and the store keeps that status across a reopen.
- property phi_status_policy: ScanPolicy | None#
The
ScanPolicythe currentphi_statuswas recorded under.It is None when the status is UNSCANNED, when the status was recorded by a store written before 1.0, and on a nested item, which is never scanned. It is stale exactly when the status is, by the same revision check.
- record_phi_status(status: PhiStatus, policy=<object object>)#
Records what a scan concluded about this entity’s current state.
Call this after any change that the status describes. Remediation changes the entity, so a REMEDIATED recorded first would stamp a revision that the entity leaves behind at once.
A new status, or the same status under a different policy (compared by value), advances the revision and leaves the entity with unsaved changes. A call with the status that the entity already carries, under the same policy, changes nothing. So an entity loaded at REMEDIATED and remediated again records nothing here. The remediation must then call
mark_modified()itself, so that the next save writes the entity.- Parameters:
status (PhiStatus) – What the scan concluded.
policy (Optional[ScanPolicy]) – The policy that the status is recorded under. Omit it to keep the policy already recorded, even when that status has gone stale.
Noneis a value, not an omission: it records “no policy”. The default is a private sentinel becauseNoneis taken (#815). Five callers pass a policy: a scan, hydration, the patient merge, a pass that settles its statuses against a report carried from another session (which records the report’s policy), and a pass that puts back the status of an entity that was already stale when the pass began (Session._keep_stale, #752).
- mark_subtree_persisted()#
Marks this entity and everything beneath it as stored.
Use it for hydration only, where a whole graph comes from the store and the claim is true of every node at once. After you commit a single row, call
mark_persisted()instead: it speaks for one entity and does not vouch for unsaved siblings.
- PhiStatus(*values)#
What the last scan concluded about an entity, and when.
It answers a different question from
has_unsaved_changes, which is persistence bookkeeping.A status is only valid for the revision that it was computed at. After an edit to the entity, the status reads UNSCANNED, because a conclusion about earlier content says nothing about the current content.
One exception: pixel redaction. Redaction records an instance’s REMEDIATED, CLEARED or IDENTIFIED again after its own writes, when that status was current before them (#896). The comparison leaves out the pixels, their descriptors, the new SOP Instance UID and its bookkeeping. It accepts the flags that redaction writes (ImageType, BurnedInAnnotation, DerivationDescription, the Derivation Code Sequence) only as they were or at exactly what redaction writes. Every other attribute and nested item must be exactly as before the pass. If anything else changed, the status is left UNSCANNED. So the anonymize, redact, export order keeps the redacted instances’ statuses.
Attributes:
Name
Type
Description
UNSCANNEDNever inspected, or inspected before the entity’s current revision.
IDENTIFIEDThe scan found identifiers here, and nothing has acted on them.
REMEDIATEDIdentifiers were found and remediation was applied.
CLEAREDThe tag scan found no identifiers. Burned-in pixel text is a separate scan, and CLEARED does not approve the entity for release.
- UNSCANNED = 'unscanned'#
Never inspected, or inspected before the entity’s current revision.
- IDENTIFIED = 'identified'#
The scan found identifiers here, and nothing has acted on them.
- REMEDIATED = 'remediated'#
Identifiers were found and remediation was applied.
- CLEARED = 'cleared'#
The scan found no identifiers. It means that the configured tag scan found nothing. It does not mean that burned-in pixel text was checked, which is a separate scan, or that the entity is approved for release.
- ScanPolicy(fingerprint: str, base: str)#
The policy a PHI status was recorded under.
A status says what a scan concluded, and a scan concludes under the rules it ran with. The store keeps the policy beside each status, so a store scanned under one configuration and exported under another says so.
fingerprintdecides whether two policies are the same. It is"v1:"and the sha256 of the policy’s canonical form, which covers what a scan reads: every rule key butname,remove_private_tagsand the configuration version.baseis what a person reads:basic@2026c,floor over basic@2026c,none, or an external profile’s path. Two policies with one fingerprint and different bases scan identically (for example, a scaffold and the bare floor). So compare fingerprints, never bases.It is frozen, so a slot that holds one is replaced whole. It is compared by value, so each audit’s fresh object equals the last one’s.
Attributes:
Name
Type
Description
fingerprintstr
"v1:"and a sha256 hex digest. Equal fingerprints scan identically.basestr
The profile the policy was built on, for a reader.
- DicomSequence(tag: str, items: List[DicomItem] = list())#
Represents a DICOM Sequence (SQ) containing multiple DicomItems.
Attributes:
Name
Type
Description
tagstr
The DICOM tag for this sequence (e.g., “0008,1111”).
itemsList[DicomItem]
A list of DicomItem objects contained in this sequence.
- clone_sequences(item: DicomItem, into: DicomItem) dict#
Deep-copies an item’s sequences, for
intoto hold.Each copied item carries its attributes and its date-shift record, and is linked to its copied container as its parent. A worker’s copy shares no sequence item with the session. Match items between copies by the
iter_item_treepath, not by identity.
- exported_patient_id(patient) str#
The Patient ID a writer puts in a file for
patient.It is
''for a subject whose files carried no Patient ID (what the source had, underKEEPandREPLACEalike). Otherwise it ispatient.patient_id. Every output path reads the Patient ID through this function: the stamp, the folder name, the WFDB record name and the instance copies. So the synthetic key, and the source Study Instance UID inside it, never reach an exported file or path.A third-party exporter (
exporters.register) calls this too, and never writespatient.patient_id. The built-ins’ write path, which applies this rule for them, does not run for a plugin. This function is documented but internal (tier 2), like the registry that it serves.- Parameters:
patient (Patient) – The patient being written.
- Returns:
The Patient ID to write, or
''for a synthetic key.- Return type:
str
- iter_item_tree(item: DicomItem, path: tuple = ())#
Yields
(item, path)foritemand every item nested below it.The walk is depth-first and in declaration order, so two copies of the same graph are walked identically. A path matches a sequence item back to the same item in another copy of the graph. Nested items carry no UID, so position is their only identity.
- Parameters:
item (DicomItem) – The root of the walk.
path (tuple) – The root’s own path, or
()for a top-level walk.
- Yields:
tuple –
(DicomItem, path), wherepathis a tuple of(sequence_tag, index)steps from the root, empty for the root itself.
- normalize_study_date(value)#
The one spelling of “text that names a day becomes a
date”.It reads the extended form
2024-01-15, which the store writes. It also reads the DICOM basic form20240115, which a hand-built graph or aDicomBuilder.add_studycall supplies.Studyapplies the same rule whenstudy_dateis assigned.- Parameters:
value (Any) – A date string, a
date, or None.- Returns:
The
datethat it names, or None for None. Anything that it cannot read comes back exactly as it was given, neither invented nor discarded.- Return type:
Any
- resolve_item_path(root: DicomItem, path: tuple) DicomItem | None#
Follows a path from
iter_item_treeback to an item, or None.The caller must treat None as “this item is gone”, never as “use the root instead”. A nested tag written onto the root fabricates a top-level element that was never in the file, and leaves the real value in place.
- Parameters:
root (DicomItem) – The item the path starts from.
path (tuple) –
(sequence_tag, index)steps. Empty or None means the root itself.
- Returns:
The item at
path, or None when the graph changed after the path was recorded (an item removed, or a sequence shortened).- Return type:
Optional[DicomItem]
- SOURCE_SOP_UID_ATTR = '_ISOCENTER_SOURCE_SOP_UID'#
Attribute key under which an instance records the SOP Instance UID it was ingested under, before UID replacement or redaction first moved it (
Instance._take_sop_uid).It is assigned into
attributesdirectly, never throughset_attr.set_attrruns the key through_canonical_tag, which lowercases it, and every reader spells it upper-case.services.pywrites_ISOCENTER_REDACTION_HASHthe same way, for the same reason.