diff --git a/docs/ann.rst b/docs/ann.rst index 9c04013ba..35a954de1 100644 --- a/docs/ann.rst +++ b/docs/ann.rst @@ -35,11 +35,13 @@ contains. The required metadata elements include: * A ``uid`` (``str`` or :class:`highdicom.UID`) uniquely identifying the group. Usually, you will want to generate a UID for this. * An ``annotated_property_category`` and ``annotated_property_type`` - (:class:`highdicom.sr.CodedConcept`), coded values (see :ref:`coding`) - describing the category and specific structure that has been annotated. - See :dcm:`CID 7151 ` and + (`pydicom.sr.coding.Code`, :class:`highdicom.sr.CodedConcept` or + :class:`highdicom.ann.AnnotatedPropertyType` for the latter), coded values + (see :ref:`coding`) describing the category and specific structure that has + been annotated. See :dcm:`CID 7151 ` and :dcm:`CID 8135 ` respectively for the associated - context groups. + context groups. Use :class:`highdicom.ann.AnnotatedPropertyType` + if you want to include modifier codes (see :ref:`ann-modifiers`). * A ``graphic_type`` (:class:`highdicom.ann.GraphicTypeValues`) indicating the "form" of the annotations. Permissible values are ``"ELLIPSE"``, ``"POINT"``, ``"POLYGON"``, ``"RECTANGLE"``, and ``"POLYLINE"``. @@ -53,12 +55,17 @@ Further optional metadata may optionally be provided, including: * An ``algorithm_identification`` (:class:`highdicom.AlgorithmIdentificationSequence`), specifying information about an algorithm that generated the annotations. -* A list of ``anatomic_regions`` (a sequence of - :class:`highdicom.sr.CodedConcept` objects), giving coded values (see - :ref:`coding`) describing regions containing the annotations. +* A list of ``anatomic_regions`` (a sequence of `pydicom.sr.coding.Code`, + :class:`highdicom.sr.CodedConcept`, or :class:`highdicom.AnatomicRegion` + objects), giving coded values (see :ref:`coding`) describing regions + containing the annotations. Use :class:`highdicom.AnatomicRegion` if you want + to include modifier codes (see :ref:`ann-modifiers`). * A list of ``primary_anatomic_structures`` (a sequence of - :class:`highdicom.sr.CodedConcept` objects) giving coded values (see - :ref:`coding`) describing anatomic structures of interest. + `pydicom.sr.coding.Code`, :class:`highdicom.sr.CodedConcept`, or + :class:`highdicom.PrimaryAnatomicStructure` objects) giving coded values (see + :ref:`coding`) describing anatomic structures of interest. Use + :class:`highdicom.PrimaryAnatomicStructure` if you want to include modifier + codes (see :ref:`ann-modifiers`). * A free-text ``description`` (``str``) of the annotation group. * A ``display_color`` (:class:`highdicom.color.CIELabColor`) giving a recommended value for viewers to use to render these annotations. This is in @@ -112,6 +119,46 @@ Here is a simple example of constructing an annotation group: Note that including two nuclei would be very unusual in practice: annotations often number in the thousands or even millions within a large whole slide image. +.. _ann-modifiers: + +Annotation Groups With Modifiers +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The annotated property type, anatomic regions, and primary anatomic structures +of an annotation group may each be accompanied by `modifier` codes that refine +their meaning, most commonly to specify laterality (see +:ref:`coding-modifiers` for background). To include modifiers, use the classes +:class:`highdicom.ann.AnnotatedPropertyType`, :class:`highdicom.AnatomicRegion` +and :class:`highdicom.PrimaryAnatomicStructure` respectively, passing the root +code and then a list of modifier codes (see :dcm:`CID 2 +` "Anatomic Modifier" for the associated context +group). + +.. code-block:: python + + # Annotations of malignant nuclei + malignant_nuclei_group = hd.ann.AnnotationGroup( + number=2, + uid=hd.UID(), + label='malignant nuclei', + annotated_property_category=codes.SCT.AnatomicalStructure, + annotated_property_type=hd.ann.AnnotatedPropertyType( + codes.SCT.Nucleus, + modifiers=[codes.SCT.Malignant], + ), + algorithm_type=hd.ann.AnnotationGroupGenerationTypeValues.MANUAL, + graphic_type=hd.ann.GraphicTypeValues.POINT, + graphic_data=graphic_data, + ) + +Anywhere that one of these classes may be used, you may still pass a plain +:class:`highdicom.sr.CodedConcept` or :class:`pydicom.sr.coding.Code`, which is +treated as a code with no modifiers. Note that the wrong class may not be used +in the wrong place: for example, passing a :class:`highdicom.AnatomicRegion` as +the ``annotated_property_type`` raises a ``TypeError``. The +``annotated_property_category`` does not support modifiers, and passing one of +the modified classes there also raises a ``TypeError``. + Including Measurements ---------------------- @@ -292,6 +339,41 @@ of matching groups, since the filters may match multiple groups. ) assert len(groups) == 1 and isinstance(groups[0], hd.ann.AnnotationGroup) +When searching by annotated property type, whether modifiers are considered +depends on the type of the value you pass: + +* If you pass a plain :class:`pydicom.sr.coding.Code` or + :class:`highdicom.sr.CodedConcept`, only the root code is compared, and any + modifiers on the group's type are ignored. Groups are matched whether or not + they have modifiers. +* If you pass a :class:`highdicom.ann.AnnotatedPropertyType`, the root code and + the complete set of modifiers (in any order) must match. An + :class:`highdicom.ann.AnnotatedPropertyType` with no modifiers therefore + matches only groups with a type that has no modifiers. + +.. code-block:: python + + # Matches any group with a "Nucleus" type, whether or not it has modifiers + groups = ann.get_annotation_groups( + annotated_property_type=codes.SCT.Nucleus, + ) + + # Matches only groups with a "Nucleus" type that has no modifiers + groups = ann.get_annotation_groups( + annotated_property_type=hd.ann.AnnotatedPropertyType( + codes.SCT.Nucleus, + ), + ) + + # Matches only groups with a "Nucleus" type with exactly the modifier + # "Malignant" + groups = ann.get_annotation_groups( + annotated_property_type=hd.ann.AnnotatedPropertyType( + codes.SCT.Nucleus, + modifiers=[codes.SCT.Malignant], + ), + ) + Extracting Information From Annotation Groups --------------------------------------------- @@ -312,8 +394,15 @@ list): # Access the UID assert group.uid == '1.2.826.0.1.3680043.10.511.3.40670836327971302375623613533993686' - # Access the annotated property type (returns a CodedConcept) - assert group.annotated_property_type == Code('84640000', 'SCT', 'Nucleus') + # Access the annotated property type (returns an AnnotatedPropertyType, + # a sub-class of CodedConcept) + assert group.annotated_property_type == codes.SCT.Nucleus + + # Any modifiers of the annotated property type are available via the + # modifiers property (an empty tuple if there are none), and the root code + # alone via the unmodified property + assert group.annotated_property_type.modifiers == () + assert group.annotated_property_type.unmodified == codes.SCT.Nucleus # Access the graphic type, describing the "form" of each annotation assert group.graphic_type == hd.ann.GraphicTypeValues.POINT diff --git a/docs/coding.rst b/docs/coding.rst index 8d42d1029..968177bc6 100644 --- a/docs/coding.rst +++ b/docs/coding.rst @@ -187,11 +187,336 @@ UCUM ---- UCUM works a little differently to the other coding schemes discussed here. -Rather than a finite set of codes, it defines codes for a set of units and a -syntax for combining them to give derived units (e.g. `"mm/s"` for millimeters -per second), meaning there are potentially infinite codes. Pydicom defines -a list of the most common units, but this will not cover every use case. +Rather than a finite set of codes, it defines codes for a set of fundamental +units and a syntax for combining them to give derived units (e.g. `"mm/s"` for +millimeters per second), meaning there are potentially infinite codes. Pydicom +defines a list of the most common units, but this will not cover every use +case. We recommend this `page `_, a useful validator for checking UCUM syntax. + +.. _coding-modifiers: + +Codes With Modifiers +-------------------- + +Some attributes in DICOM allow a code to be accompanied by one or more +`modifier` codes that refine the meaning of the root code. A typical example is +laterality: rather than needing a separate code for "left kidney" and "right +kidney", you can use the single code for "kidney" together with the modifier +"left" or "right". The codes used as modifiers are generally drawn from +:dcm:`CID 2 ` "Anatomic Modifier". + +In the DICOM standard, each place where modifiers are allowed has its own +sequence attribute for holding them (for example "Segmented Property Type +Modifier Code Sequence" next to "Segmented Property Type Code Sequence"). +`Highdicom` provides a class for each such attribute. They are all +sub-classes of :class:`highdicom.sr.CodedConcept`, and are constructed from a +root code and an optional sequence of modifier codes (either +``pydicom.sr.coding.Code`` or :class:`highdicom.sr.CodedConcept` objects): + +.. list-table:: + :header-rows: 1 + + * - Class + - Describes + - Used in + * - :class:`highdicom.seg.SegmentedPropertyType` + - The property that a segment represents + (:dcm:`CID 7151 `) + - :class:`highdicom.seg.SegmentDescription` (see :ref:`seg-modifiers`) + * - :class:`highdicom.ann.AnnotatedPropertyType` + - The property that an annotation group represents + (:dcm:`CID 8135 `) + - :class:`highdicom.ann.AnnotationGroup` (see :ref:`ann-modifiers`) + * - :class:`highdicom.AnatomicRegion` + - The anatomic region into which an object falls + (e.g. :dcm:`CID 4 `) + - :class:`highdicom.seg.SegmentDescription` and + :class:`highdicom.ann.AnnotationGroup` + * - :class:`highdicom.PrimaryAnatomicStructure` + - The anatomic structure that an object represents + - :class:`highdicom.seg.SegmentDescription` and + :class:`highdicom.ann.AnnotationGroup` + +Each class stores its modifiers in the attribute with the corresponding +standard name, so that the object can be placed directly into a DICOM dataset. +The classes are not interchangeable: for example an +:class:`highdicom.AnatomicRegion` cannot be used where a +:class:`highdicom.seg.SegmentedPropertyType` is expected, and doing so raises a +``TypeError``. + +To create an instance of one of these classes, pass a +``pydicom.sr.coding.Code`` or :class:`highdicom.sr.CodedConcept` to serve as +the root concept, then optionally a list of further codes to the `modifiers` +parameter. + +.. code-block:: python + + import highdicom as hd + from pydicom.sr.codedict import codes + + # A segmented property type of "Kidney", modified by "Left" + left_kidney = hd.seg.SegmentedPropertyType( + codes.SCT.Kidney, + modifiers=[codes.SCT.Left], + ) + + # The value, meaning, and scheme_designator properties behave as they do + # for a plain CodedConcept + print(left_kidney.scheme_designator, left_kidney.value, left_kidney.meaning) + # SCT 64033007 Kidney + + # Access the modifiers using the modifiers property (this is the same for + # every one of the classes above) + print([m.meaning for m in left_kidney.modifiers]) + # ['Left'] + + # Access the root code on its own, without the modifiers + assert left_kidney.unmodified == codes.SCT.Kidney + +Two modified codes are equal if they have the same root code and the same set +of modifiers. The order of the modifiers is not significant, and the class of +the modified code (e.g. :class:`highdicom.seg.SegmentedPropertyType` or +:class:`highdicom.AnatomicRegion`) is not considered. The hash is consistent +with this definition, so these objects may be used in sets and as dictionary +keys. + +.. code-block:: python + + a = hd.seg.SegmentedPropertyType( + codes.SCT.Kidney, + modifiers=[codes.SCT.Left, codes.SCT.Posterior], + ) + b = hd.seg.SegmentedPropertyType( + codes.SCT.Kidney, + modifiers=[codes.SCT.Posterior, codes.SCT.Left], + ) + assert a == b + assert len({a, b}) == 1 + + # Different modifiers means a different code + assert a != hd.seg.SegmentedPropertyType(codes.SCT.Kidney) + +A modified code that has no modifiers is considered equal to the plain code, +but one that has modifiers does not. When you want to compare only the root +code regardless of modifiers, use the ``unmodified`` property or the +``ignore_modifiers`` option of :func:`highdicom.sr.codes_equal`: + +.. code-block:: python + + assert hd.seg.SegmentedPropertyType(codes.SCT.Kidney) == codes.SCT.Kidney + assert a != codes.SCT.Kidney + assert a.unmodified == codes.SCT.Kidney + assert hd.sr.codes_equal(a, codes.SCT.Kidney, ignore_modifiers=True) + +.. _coding-gotcha: + +Gotcha: Comparing With ``pydicom.sr.coding.Code`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The ``==`` operator is **not symmetric** when a code with modifiers is compared +with a ``pydicom.sr.coding.Code``. When the ``Code`` is on the left, the +comparison is evaluated by `pydicom`, whose ``Code`` class knows nothing about +modifiers (and is not under the control of `highdicom`), so the modifiers are +silently ignored: + +.. code-block:: python + + left_kidney = hd.seg.SegmentedPropertyType( + codes.SCT.Kidney, + modifiers=[codes.SCT.Left], + ) + + # The modifiers are considered: not equal + assert left_kidney != codes.SCT.Kidney + + # The modifiers are not considered, since pydicom evaluates this: equal! + assert codes.SCT.Kidney == left_kidney + +This also affects code that compares implicitly, such as ``code in +list_of_codes``, ``list_of_codes.index(code)`` and the order of operands in an +``assert expected == actual`` statement. Comparing two +:class:`highdicom.sr.CodedConcept` objects (or objects of any of its +sub-classes) does not have this problem, because the operator of the +sub-class is always tried first. + +To compare codes safely in every situation, use the function +:func:`highdicom.sr.codes_equal`. It gives the same result regardless of the +order of its arguments and of the types of its arguments, and treats a plain +``Code`` as having no modifiers: + +.. code-block:: python + + assert not hd.sr.codes_equal(left_kidney, codes.SCT.Kidney) + assert not hd.sr.codes_equal(codes.SCT.Kidney, left_kidney) + + # Compare only the root codes, ignoring modifiers + assert hd.sr.codes_equal( + codes.SCT.Kidney, + left_kidney, + ignore_modifiers=True, + ) + +The behavior of the ``==`` operator for the possible combinations of types is +summarized below. + +.. list-table:: + :header-rows: 1 + + * - Expression + - Considers modifiers? + * - ``CodedConcept == CodedConcept`` (or any sub-class) + - Yes + * - ``modified_code == Code`` + - Yes + * - ``Code == modified_code`` + - **No** + * - ``hd.sr.codes_equal(a, b)``, any types, either order + - Yes (unless ``ignore_modifiers=True``) + +.. _coding-scheme-identification: + +Coding Scheme Identification +---------------------------- + +Every code in a DICOM object carries only the *designator* of its coding scheme +(e.g. ``"SCT"``), not a full definition of the scheme. For the schemes that are +listed within the DICOM standard itself (those on `this page +`_, +including ``"DCM"``, ``"SCT"``, ``"LN"``, ``"UCUM"`` and others), the +designator is enough for a reader to know exactly which terminology is meant. +It is valid to use other coding schemes, but then the designator may not be +understood by the recipient of the file. In this case, it is a best practice to +place information describing the scheme(s) used in the instance's "Coding +Scheme Identification Sequence". This sequence maps each designator used within +an instance to more information about the scheme, including the scheme's full +name, its version, the organization responsible for it, a UID or external +registry identifier, and links to resources describing it. + +In highdicom, each coding scheme may be described by an item of type +:class:`highdicom.coding_schemes.CodingSchemeIdentificationItem`. Only the +``designator`` is required, but you should provide as much additional +information as you can. Pass a sequence of such items to the ``coding_schemes`` +parameter of the constructor of :class:`highdicom.SOPClass`, and they will be +placed into the Coding Scheme Identification Sequence of the new object. The +constructors of all IODs implemented in highdicom (such as the SR, Parametric +Map and Segmentation classes) accept a ``coding_schemes`` argument (via the +``**kwargs`` argument, which forwards arguments to :class:`highdicom.SOPClass`). +Below, we show two examples of this, one for publicly available coding schemes +listed in a public registry, the other for private codes that are only used +within a particular organization. + +.. _public-coding-scheme: + +Publicly Registered Coding Scheme +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +For a scheme that is registered in an external registry, use the ``registry`` +parameter, and additionally specify **either** the ``uid`` of the scheme (if +it has an ISO 8824 object identifier compatible with the DICOM UI value +representation) **or** its identifier within the registry as ``external_id``. +It is an error to give both, or neither, when ``registry`` is used: + +.. code-block:: python + + hl7_scheme = CodingSchemeIdentificationItem( + designator="ICD10", + name="International Classification of Diseases, 10th Revision", + registry="HL7", + uid="2.16.840.1.113883.6.3", + ) + +Each designator used in the instance should be described by at most one item. + +.. _coding-private-codes: + +Private Codes +^^^^^^^^^^^^^ + +If no existing terminology contains the concept you need to describe, you may +define your own "private" or "local" codes. Doing so should be a last resort, +since other software will not be able to interpret them. Before creating +private codes, look through the terminologies above (and the +tools described in `Finding Suitable Codes`_) for a suitable existing code. When +you do need to create them: + +- **Designator**: the DICOM standard reserves coding scheme designators + starting with ``"99"`` for private use (e.g. ``"99MYORG"``). Choose a + designator that is specific to your organization or project to avoid + collisions with those of other users. The designator is a DICOM Short String, + so it may be at most 16 characters long, and it must not contain backslashes + or control characters. +- **Value**: any code value that is unique within your scheme, up to 16 + characters. It need not be numeric. +- **Meaning**: a human-readable description of the concept. Because receivers + cannot look the code up elsewhere, make this clear and complete. +- **Version**: if your scheme is likely to change over time, set + ``scheme_version`` on the code so that its meaning is unambiguous. +- **Identification**: describe the scheme with a + :class:`highdicom.coding_schemes.CodingSchemeIdentificationItem` as above, + so that readers can discover who defines the scheme and where to find its + documentation. The designator of every code used in the instance that is not + from a standard terminology (``"99MYORG"`` here) should have a matching + ``CodingSchemeIdentificationItem`` in the ``coding_schemes`` list. + +Putting this together, the following creates a private code and an instance +that uses it and describes its scheme. This example skips over most of the +detail on how to create the Structured Report instance to focus on the use of +the coding scheme. See :ref:`sr` for a full explanation of SRs. + +.. code-block:: python + + import highdicom as hd + from highdicom.coding_schemes import ( + CodingSchemeIdentificationItem, + CodingSchemeResourceItem, + ) + from highdicom.enum import CodingSchemeURLTypeValues + + + # An example coded concept using a private coding scheme. This can + # be used anywhere a CodedConcept may be passed + private_motion_artifact_code = hd.sr.CodedConcept( + value="FIND-0042", + scheme_designator="99MYORG", + meaning="Suspected motion artifact", + scheme_version="2.1", + ) + + # Define a CodingSchemeIdentificationItem that describes this private coding + # scheme, with the designator matching that used above + my_scheme = CodingSchemeIdentificationItem( + designator="99MYORG", + name="My Organization Findings Terminology", + version="2.1", + responsible_organization="My Organization, contact@example.com", + resources=[ + CodingSchemeResourceItem( + url="https://example.com/terminology/v2.1/description.html", + url_type=CodingSchemeURLTypeValues.DOC, + ), + CodingSchemeResourceItem( + url="https://example.com/terminology/v2.1/terms.csv", + url_type=CodingSchemeURLTypeValues.CSV, + ), + ], + ) + + # Pass the coding scheme to the constructor of any highdicom IOD, here a + # structured report as an example + instance = hd.sr.Comprehensive3DSR( + content=MeasurementReport( + imaging_measurements=[ + hd.sr.MeasurementsAndQualitativeEvaluations( + ..., + finding_type=private_motion_artifact_code, + ) + ], + ..., + ), + ..., + coding_schemes=[my_scheme], + ) diff --git a/docs/images/tid1500_overview.svg b/docs/images/tid1500_overview.svg index 3482a4a5d..e44ab4cea 100644 --- a/docs/images/tid1500_overview.svg +++ b/docs/images/tid1500_overview.svg @@ -401,9 +401,9 @@ - Finding Sites Contains 1 - Contains 0-n - Contains 0-n + + Contains 0-n Evaluation - - - - + + + + - - + + + + + + + + Contains 0-n + + Contains 0-n + + Contains 0-n + + Text Evaluation + - Free Text Evaluation diff --git a/docs/package.rst b/docs/package.rst index 9dd22c5a3..efc6c181e 100644 --- a/docs/package.rst +++ b/docs/package.rst @@ -93,6 +93,17 @@ highdicom.pixels module :undoc-members: :show-inheritance: +highdicom.coding_schemes module ++++++++++++++++++++++++++++++++ + +.. automodule:: highdicom.coding_schemes + :members: + :inherited-members: pydicom.dataset.Dataset,pydicom.sequence.Sequence,Dataset,Sequence,list,str,DataElementSequence,enum.Enum,Enum, + :exclude-members: copy_patient_and_study_information,copy_specimen_information + :special-members: __call__ + :undoc-members: + :show-inheritance: + .. _highdicom-legacy-subpackage: highdicom.legacy package diff --git a/docs/quickstart.rst b/docs/quickstart.rst index 0f0ee5fc5..9b5ab57a1 100644 --- a/docs/quickstart.rst +++ b/docs/quickstart.rst @@ -936,7 +936,6 @@ labeled bounding box region drawn over a CT image. ref_dataset=image_dataset, pixel_array=pixel_array, photometric_interpretation=hd.PhotometricInterpretationValues.RGB, - bits_allocated=8, coordinate_system=hd.CoordinateSystemNames.PATIENT, series_instance_uid=hd.UID(), sop_instance_uid=hd.UID(), @@ -998,7 +997,6 @@ overlay a segmentation that is stored in a NumPy array called "seg_out". sc_image = hd.sc.SCImage( pixel_array=pixel_array.astype(np.uint8), photometric_interpretation=hd.PhotometricInterpretationValues.RGB, - bits_allocated=8, coordinate_system=hd.CoordinateSystemNames.PATIENT, study_instance_uid=study_instance_uid, series_instance_uid=series_instance_uid, diff --git a/docs/release_notes.rst b/docs/release_notes.rst index 7a7f49144..a070b8247 100644 --- a/docs/release_notes.rst +++ b/docs/release_notes.rst @@ -243,3 +243,167 @@ can be replaced with this to give the same output object: ], ..., ) + +Deprecation of ``bits_allocated`` parameter in ``SCImage`` +---------------------------------------------------------- + +Until highdicom 0.29.0, the constructor of :class:`highdicom.sc.SCImage` (and +its classmethod :meth:`highdicom.sc.SCImage.from_ref_dataset()`) had a required +parameter named ``bits_allocated``. However, there were several issues with +this. Firstly, it would accept a value of 12, which is not valid for use with +Bits Allocated. For other values, it had to match exactly the number of bits in +the datatype of the ``pixel_array`` parameter, making it serve no useful +purpose other than make the API more complex for users. + +In version 0.29.0, the parameter was deprecated. The number of bits allocated +is now inferred from the datatype of ``pixel_array``. By default, the number of +bits stored will match the number of bits allocated. A new keyword-only +``bits_stored`` parameter allows you to specify a number of bits stored that +differs from the number of bits allocated. To minimize disruption for existing +code, the constructor will continue to accept ``bits_allocated`` as a keyword +parameter, and treat it as if the same value were passed to ``bits_stored``, +but issue a warning instructing the user to update the code. + +Unfortunately, code that passes ``bits_allocated`` as a positional argument +will break with this change. In this case, users should either remove this +argument entirely to have bits allocated and bits stored inferred from the +pixel array, or specify ``bits_stored`` instead. + +.. _cielab-d50: + +CIELab Conversions Now Use The D50 White Point +---------------------------------------------- + +DICOM encodes CIELab values (such as Recommended Display CIELab Value) in the +same way as the ICC Profile Connection Space (see :dcm:`PS3.3 C.10.7.1.1 +`), i.e. relative to the D50 +illuminant, whereas the native white point of sRGB is D65. + +Prior to highdicom 0.29.0, the conversions implemented by +:class:`highdicom.color.CIELabColor` (``from_rgb``, ``from_string`` and +``to_rgb``) omitted the chromatic adaptation between the two white points and +therefore produced CIELab values relative to D65. From highdicom 0.29.0, sRGB +values are linearized, converted to CIE XYZ (D65), chromatically adapted to +D50 using the linear Bradford transform, and only then converted to CIELab +(and vice versa). The matrices and constants used are those of the `CSS Color +Module Level 4 sample code +`_, matching the +behavior of DCMTK (changed after version 3.7.0) and PixelMed. + +No code changes are required, but note that the CIELab values stored in files +created with highdicom 0.29.0 and later differ slightly from those created +with earlier versions for the same RGB input. Neutral (gray) colors are +unaffected; for chromatic colors the a* and b* components change. For example, +pure red (255, 0, 0) was previously encoded as L*a*b* (53.23, 80.11, 67.22) +and is now encoded as (54.29, 80.81, 69.89). + +.. _modified-codes: + +Codes With Modifiers in Segmentation and Annotation Objects +----------------------------------------------------------- + +In highdicom 0.29.0, the segmented property type of a segment (in +:class:`highdicom.seg.SegmentDescription`), the annotated property type of an +annotation group (in :class:`highdicom.ann.AnnotationGroup`), and the anatomic +regions and primary anatomic structures of both, may include modifier codes +(for example to specify laterality) via the new classes +:class:`highdicom.seg.SegmentedPropertyType`, +:class:`highdicom.ann.AnnotatedPropertyType`, +:class:`highdicom.AnatomicRegion` and +:class:`highdicom.PrimaryAnatomicStructure`. See :ref:`coding-modifiers`, +:ref:`seg-modifiers` and :ref:`ann-modifiers` for details. + +Existing code continues to work without modification, but some behavior has +changed: + +* The properties + :attr:`highdicom.seg.SegmentDescription.segmented_property_type`, + :attr:`highdicom.seg.SegmentDescription.anatomic_regions`, + :attr:`highdicom.seg.SegmentDescription.primary_anatomic_structures`, + :attr:`highdicom.ann.AnnotationGroup.annotated_property_type`, + :attr:`highdicom.ann.AnnotationGroup.anatomic_regions`, + :attr:`highdicom.ann.AnnotationGroup.primary_anatomic_structures` and + :attr:`highdicom.seg.Segmentation.segmented_property_types` now return + instances of the new sub-classes of :class:`highdicom.sr.CodedConcept`, + rather than plain :class:`highdicom.sr.CodedConcept` objects. These can be + used in the same way, and additionally have ``modifiers`` and ``unmodified`` + properties. +* When searching with the ``segmented_property_type`` argument of + :meth:`highdicom.seg.Segmentation.get_segment_numbers` and + :meth:`highdicom.seg.Segmentation.get_tracking_ids`, or the + ``annotated_property_type`` argument of + :meth:`highdicom.ann.MicroscopyBulkSimpleAnnotations.get_annotation_groups`, + a plain :class:`pydicom.sr.coding.Code` or + :class:`highdicom.sr.CodedConcept` matches the root code only (ignoring any + modifiers, as before), whereas an instance of the new class with modifiers + must match the modifiers as well. +* A code that has modifiers is not equal (using ``==``) to the same root code + without modifiers. Be aware that, because the ``==`` operator of + ``pydicom.sr.coding.Code`` cannot be changed by highdicom, the expression + ``Code == modified_code`` ignores the modifiers, whereas + ``modified_code == Code`` does not. To compare codes in a way that is safe + in all situations, use the new function :func:`highdicom.sr.codes_equal`. + See :ref:`coding-gotcha`. + +To compare only root codes in existing code, either use +:func:`highdicom.sr.codes_equal` with ``ignore_modifiers=True`` or compare the +``unmodified`` property: + +.. code-block:: python + + import highdicom as hd + from pydicom.sr.codedict import codes + + seg = hd.seg.segread('path/to/seg.dcm') + desc = seg.get_segment_description(1) + + # Compares the root code only, whether or not the segment has modifiers + assert hd.sr.codes_equal( + desc.segmented_property_type, + codes.SCT.Kidney, + ignore_modifiers=True, + ) + assert desc.segmented_property_type.unmodified == codes.SCT.Kidney + +.. _match-geometry-tolerances: + +Tolerances in ``match_geometry`` +-------------------------------- + +In highdicom 0.29.0, the ``tol`` parameter of +:meth:`highdicom.Volume.match_geometry` and +:meth:`highdicom.VolumeGeometry.match_geometry` is deprecated. It previously +governed both the voxel spacing and the position comparisons using a very +tight default of ``1e-5`` that often caused spurious failures with real DICOM +data. It is replaced by three more specific parameters: + +* ``spacing_tol`` (default ``1e-3``): the ratio of the two volumes' voxel + spacings must be within ``spacing_tol * n`` of the nearest integer ``n``, so + the tolerance is relative to the step size. +* ``position_tol`` (default ``1e-2``): the translation between the volumes + must be within this fraction of a voxel of a whole number of voxels. This + is also applied to the misalignment at the far end of the grid, so that + small spacing differences that accumulate across a volume are detected. +* ``parallel_tol``: the tolerance used when deciding whether direction + vectors are parallel. + +Passing ``tol`` still works but emits a ``DeprecationWarning`` and sets both +``spacing_tol`` and ``position_tol`` to the given value. To update your code, +replace ``tol`` with the new parameters: + +.. code-block:: python + + # Before + matched = volume.match_geometry(other, tol=1e-4) + + # After + matched = volume.match_geometry( + other, + spacing_tol=1e-4, + position_tol=1e-4, + ) + +Note that the new defaults are more permissive for rounding error in +individual positions and spacings, but the far-end alignment check may reject +large volumes with slightly inexact spacings that were previously accepted. If +this occurs, increase ``position_tol``. diff --git a/docs/seg.rst b/docs/seg.rst index 4aff4caaa..02c5aacd1 100644 --- a/docs/seg.rst +++ b/docs/seg.rst @@ -61,11 +61,15 @@ description includes the following information: :class:`highdicom.sr.CodedConcept`, or a :class:`pydicom.sr.coding.Code` object. See :dcm:`CID 7150 ` for the associated context group. + Modifiers are not permitted for this value. - **Segmented Property Type**: Another coded value that more specifically describes the segmented region, as for example a kidney or tumor. This is - passed as either a :class:`highdicom.sr.CodedConcept`, or a - :class:`pydicom.sr.coding.Code` object. See + passed as either a :class:`highdicom.sr.CodedConcept`, a + :class:`pydicom.sr.coding.Code`, or a + :class:`highdicom.seg.SegmentedPropertyType` object. See :dcm:`CID 7151 ` for the associated context group. + Use :class:`highdicom.seg.SegmentedPropertyType` if you want to include + modifier codes, such as laterality (see :ref:`seg-modifiers`). - **Algorithm Type**: Whether the segment was produced by an automatic, semi-automatic, or manual algorithm. The valid values are contained within the enum :class:`highdicom.seg.SegmentAlgorithmTypeValues`. @@ -73,8 +77,18 @@ description includes the following information: in which the segment is found. For example, if the segmented property type is "tumor", this can be used to convey that the tumor is found in the kidney. This is passed as a sequence of coded values as either - :class:`highdicom.sr.CodedConcept`, or :class:`pydicom.sr.coding.Code` - objects. + :class:`highdicom.sr.CodedConcept`, :class:`pydicom.sr.coding.Code`, or + :class:`highdicom.AnatomicRegion` objects. Use + :class:`highdicom.AnatomicRegion` to include modifier codes (see + :ref:`seg-modifiers`). +- **Primary Anatomic Structures**: (Optional) A coded value describing the + anatomic structure that the segment represents, where this is more specific + than the segmented property type. This is passed as a sequence of coded + values as either :class:`highdicom.sr.CodedConcept`, + :class:`pydicom.sr.coding.Code`, or + :class:`highdicom.PrimaryAnatomicStructure` objects. Use + :class:`highdicom.PrimaryAnatomicStructure` to include modifier codes (see + :ref:`seg-modifiers`). - **Tracking ID and UID**: (Optional) These allow you to provide identifiers for a specific segment. TrackingID is intended as a human readable ID unique within a particular setting (e.g. a particular healthcare institution or @@ -151,6 +165,50 @@ elsewhere. For a description of how to access segment metadata in existing segmentations, see :ref:`segment_description_parsing`. +.. _seg-modifiers: + +Segment Descriptions With Modifiers +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The segmented property type, anatomic regions, and primary anatomic structures +of a segment may each be accompanied by `modifier` codes that refine their +meaning, most commonly to specify laterality (see :ref:`coding-modifiers` for +background). To include modifiers, use the classes +:class:`highdicom.seg.SegmentedPropertyType`, +:class:`highdicom.AnatomicRegion`, and +:class:`highdicom.PrimaryAnatomicStructure` respectively, passing the root code +and then a list of modifier codes (see :dcm:`CID 2 +` "Anatomic Modifier" for the associated context +group). + +.. code-block:: python + + # An example description of a lung nodule that uses a modifier on the + # primary anatomic structure to specify that it is found in the left + # lung + lung_nodule_description = hd.seg.SegmentDescription( + segment_number=3, + segment_label='lung nodule', + segmented_property_category=codes.SCT.MorphologicallyAbnormalStructure, + segmented_property_type=codes.SCT.Nodule, + algorithm_type=hd.seg.SegmentAlgorithmTypeValues.MANUAL, + anatomic_regions=[codes.SCT.Chest], + primary_anatomic_structures=[ + hd.PrimaryAnatomicStructure( + codes.SCT.Lung, + modifiers=[codes.SCT.Left], + ), + ], + ) + +Anywhere that one of these classes may be used, you may still pass a plain +:class:`highdicom.sr.CodedConcept` or :class:`pydicom.sr.coding.Code`, which is +treated as a code with no modifiers. Note that the wrong class may not be used +in the wrong place: for example, passing a +:class:`highdicom.AnatomicRegion` as the ``segmented_property_type`` raises a +``TypeError``. The ``segmented_property_category`` does not support modifiers. + + Segmentation Type (Binary, Fractional and Labelmap) --------------------------------------------------- @@ -1433,6 +1491,31 @@ understand the meaning of each segment (for an overview of the metadata see assert segment_description.segmented_property_category == codes.SCT.Tissue assert segment_description.segmented_property_type == codes.SCT.Bone + # The segmented property type is returned as a + # highdicom.seg.SegmentedPropertyType, which also provides access to any + # modifier codes (an empty tuple if there are none). The same applies to + # the anatomic_regions (highdicom.AnatomicRegion) and + # primary_anatomic_structures (highdicom.PrimaryAnatomicStructure) + # properties, which return lists + property_type = segment_description.segmented_property_type + assert isinstance(property_type, hd.seg.SegmentedPropertyType) + assert property_type.modifiers == () + assert property_type.unmodified == codes.SCT.Bone + +For segments whose descriptions include modifiers (see :ref:`seg-modifiers`), +the modifiers are available via the ``modifiers`` property of these objects: + +.. code-block:: python + + for modifier in segment_description.segmented_property_type.modifiers: + print(modifier.meaning) + +You can also list all the unique segmented property types in a segmentation +using the :attr:`highdicom.seg.Segmentation.segmented_property_types` +property, which returns a list of :class:`highdicom.seg.SegmentedPropertyType` +objects. Property types with the same root code but different modifiers are +listed separately. + Searching For Segments ---------------------- @@ -1455,28 +1538,69 @@ whose descriptions meet certain criteria. For example: assert seg.number_of_segments == 2 # Check the range of segment numbers - assert seg.segment_numbers == range(1, 3) + assert seg.segment_numbers == [1, 2] # Search for segments by label (returns segment numbers of all matching # segments) - assert seg.get_segment_numbers(segment_label='first segment')) == [1] - assert seg.get_segment_numbers(segment_label='second segment')) == [2] + assert seg.get_segment_numbers(segment_label='first segment') == [1] + assert seg.get_segment_numbers(segment_label='second segment') == [2] # Search for segments by segmented property type (returns segment numbers # of all matching segments) - assert seg.get_segment_numbers(segmented_property_type=codes.SCT.Bone)) == [1] - assert seg.get_segment_numbers(segmented_property_type=codes.SCT.Spine)) == [2] + assert seg.get_segment_numbers(segmented_property_type=codes.SCT.Bone) == [1] + assert seg.get_segment_numbers(segmented_property_type=codes.SCT.Spine) == [2] + + # Search for segments by segmented property type, including modifiers (see + # below) + left_bone = hd.seg.SegmentedPropertyType( + codes.SCT.Bone, + modifiers=[codes.SCT.Left], + ) + assert seg.get_segment_numbers(segmented_property_type=left_bone) == [] # Search for segments by tracking UID (returns segment numbers of all # matching segments) - assert seg.get_segment_numbers(tracking_uid='1.2.826.0.1.3680043.10.511.3.83271046815894549094043330632275067')) == [1] - assert seg.get_segment_numbers(tracking_uid='1.2.826.0.1.3680043.10.511.3.10042414969629429693880339016394772')) == [2] + assert seg.get_segment_numbers(tracking_uid='1.2.826.0.1.3680043.10.511.3.83271046815894549094043330632275067') == [1] + assert seg.get_segment_numbers(tracking_uid='1.2.826.0.1.3680043.10.511.3.10042414969629429693880339016394772') == [2] # You can also get the full description for a given segment, and access # the information in it via properties segment_1_description = seg.get_segment_description(1) - assert segment_1_description.segment_label) == 'first segment' - assert segment_1_description.tracking_uid) == '1.2.826.0.1.3680043.10.511.3.83271046815894549094043330632275067' + assert segment_1_description.segment_label == 'first segment' + assert segment_1_description.tracking_uid == '1.2.826.0.1.3680043.10.511.3.83271046815894549094043330632275067' + +When searching by segmented property type, whether modifiers are considered +depends on the type of the value you pass: + +* If you pass a plain :class:`pydicom.sr.coding.Code` or + :class:`highdicom.sr.CodedConcept`, only the root code is compared, and any + modifiers on the segment's type are ignored. Segments are matched whether or + not they have modifiers. +* If you pass a :class:`highdicom.seg.SegmentedPropertyType`, the root code and + the complete set of modifiers (in any order) must match. A + :class:`highdicom.seg.SegmentedPropertyType` with no modifiers therefore + matches only segments with a type that has no modifiers. + +.. code-block:: python + + # Matches all segments of type "Kidney" with or without modifiers + seg.get_segment_numbers(segmented_property_type=codes.SCT.Kidney) + + # Matches only segments of type "Kidney" with no modifiers + seg.get_segment_numbers( + segmented_property_type=hd.seg.SegmentedPropertyType(codes.SCT.Kidney) + ) + + # Matches only segments of type "Kidney" with exactly the modifier "Left" + seg.get_segment_numbers( + segmented_property_type=hd.seg.SegmentedPropertyType( + codes.SCT.Kidney, + modifiers=[codes.SCT.Left], + ) + ) + +The same rules apply to the ``segmented_property_type`` argument of +:meth:`highdicom.seg.Segmentation.get_tracking_ids()`. .. _seg-get-pixels: diff --git a/docs/tid1500.rst b/docs/tid1500.rst index bc1abc800..3afcd4711 100644 --- a/docs/tid1500.rst +++ b/docs/tid1500.rst @@ -53,7 +53,10 @@ group). Each Measurement Group contains a number of Measurements (`TID300 `_) - numerical values derived from an image, such as a length or volume - and/or Qualitative Evaluations - categorical values derived -from an image, such as classification of a tumor morphology. +from an image, such as classification of a tumor morphology. The standard also +allows qualitative evaluations with free text values, which *highdicom* calls +text evaluations, but coded qualitative qvaluations should be preferred +where possible. When constructing the content, it is necessary to start at the bottom of the content tree with the Measurements and Evaluations and work up, by adding them @@ -166,8 +169,8 @@ The following is a simple example: # A tracking identifier for this measurement group tracking_id = hd.sr.TrackingIdentifier( - identifier='Image0001', - uid=hd.UID(), + identifier='Image0001', + uid=hd.UID(), ) # An object describing the source image for the measurements @@ -175,10 +178,10 @@ The following is a simple example: # Construct the measurement group group = hd.sr.MeasurementsAndQualitativeEvaluations( - source_images=[source_image], - tracking_identifier=tracking_id, - measurements=[...], - qualitative_evaluations=[...], + source_images=[source_image], + tracking_identifier=tracking_id, + measurements=[...], + qualitative_evaluations=[...], ) Planar ROI Image Measurements Group (`TID1410 `_) @@ -223,23 +226,23 @@ The following example uses an :class:`highdicom.sr.ImageRegion` as the # A tracking identifier for this measurement group tracking_id = hd.sr.TrackingIdentifier( - identifier='Region0001', - uid=hd.UID(), + identifier='Region0001', + uid=hd.UID(), ) # Define the image region (a circle) using image coordinates region = hd.sr.ImageRegion( - graphic_type=hd.sr.GraphicTypeValues.CIRCLE, - graphic_data=np.array([[45.0, 55.0], [45.0, 65.0]]), - source_image=hd.sr.SourceImageForRegion.from_source_image(im), + graphic_type=hd.sr.GraphicTypeValues.CIRCLE, + graphic_data=np.array([[45.0, 55.0], [45.0, 65.0]]), + source_image=hd.sr.SourceImageForRegion.from_source_image(im), ) # Construct the measurement group group = hd.sr.PlanarROIMeasurementsAndQualitativeEvaluations( - referenced_region=region, - tracking_identifier=tracking_id, - measurements=[...], - qualitative_evaluations=[...], + referenced_region=region, + tracking_identifier=tracking_id, + measurements=[...], + qualitative_evaluations=[...], ) This example uses an :class:`highdicom.sr.ImageRegion3D` as the @@ -255,23 +258,23 @@ This example uses an :class:`highdicom.sr.ImageRegion3D` as the # A tracking identifier for this measurement group tracking_id = hd.sr.TrackingIdentifier( - identifier='Region3D0001', - uid=hd.UID(), + identifier='Region3D0001', + uid=hd.UID(), ) # Define the image region (a point) using frame-of-reference coordinates region = hd.sr.ImageRegion3D( - graphic_type=hd.sr.GraphicTypeValues3D.POINT, - graphic_data=np.array([[123.5, 234.1, -23.7]]), - frame_of_reference_uid=im.FrameOfReferenceUID, + graphic_type=hd.sr.GraphicTypeValues3D.POINT, + graphic_data=np.array([[123.5, 234.1, -23.7]]), + frame_of_reference_uid=im.FrameOfReferenceUID, ) # Construct the measurement group group = hd.sr.PlanarROIMeasurementsAndQualitativeEvaluations( - referenced_region=region, - tracking_identifier=tracking_id, - measurements=[...], - qualitative_evaluations=[...], + referenced_region=region, + tracking_identifier=tracking_id, + measurements=[...], + qualitative_evaluations=[...], ) The final example uses an :class:`highdicom.sr.ReferencedSegmentationFrame` as @@ -292,22 +295,22 @@ the ``referenced_segment``: # A tracking identifier for this measurement group tracking_id = hd.sr.TrackingIdentifier( - identifier='Region3D0001', - uid=hd.UID(), + identifier='Region3D0001', + uid=hd.UID(), ) # Define the image region using a specific segment from the segmentation ref_segment = hd.sr.ReferencedSegmentationFrame.from_segmentation( - segmentation=seg, - segment_number=1, + segmentation=seg, + segment_number=1, ) # Construct the measurement group group = hd.sr.PlanarROIMeasurementsAndQualitativeEvaluations( - referenced_segment=ref_segment, - tracking_identifier=tracking_id, - measurements=[...], - qualitative_evaluations=[...], + referenced_segment=ref_segment, + tracking_identifier=tracking_id, + measurements=[...], + qualitative_evaluations=[...], ) Volumetric ROI Image Measurements Group (`TID1411 `_) @@ -353,28 +356,28 @@ as the ``referenced_regions``: # A tracking identifier for this measurement group tracking_id = hd.sr.TrackingIdentifier( - identifier='Region0001', - uid=hd.UID(), + identifier='Region0001', + uid=hd.UID(), ) # Define the image regions (a circle in two images) using image coordinates region1 = hd.sr.ImageRegion( - graphic_type=hd.sr.GraphicTypeValues.CIRCLE, - graphic_data=np.array([[45.0, 55.0], [45.0, 65.0]]), - source_image=hd.sr.SourceImageForRegion.from_source_image(im1), + graphic_type=hd.sr.GraphicTypeValues.CIRCLE, + graphic_data=np.array([[45.0, 55.0], [45.0, 65.0]]), + source_image=hd.sr.SourceImageForRegion.from_source_image(im1), ) region2 = hd.sr.ImageRegion( - graphic_type=hd.sr.GraphicTypeValues.CIRCLE, - graphic_data=np.array([[40.0, 50.0], [40.0, 60.0]]), - source_image=hd.sr.SourceImageForRegion.from_source_image(im2), + graphic_type=hd.sr.GraphicTypeValues.CIRCLE, + graphic_data=np.array([[40.0, 50.0], [40.0, 60.0]]), + source_image=hd.sr.SourceImageForRegion.from_source_image(im2), ) # Construct the measurement group group = hd.sr.VolumetricROIMeasurementsAndQualitativeEvaluations( - referenced_regions=[region1, region2], - tracking_identifier=tracking_id, - measurements=[...], - qualitative_evaluations=[...], + referenced_regions=[region1, region2], + tracking_identifier=tracking_id, + measurements=[...], + qualitative_evaluations=[...], ) This example uses a :class:`highdicom.sr.VolumeSurface` object as the @@ -390,8 +393,8 @@ This example uses a :class:`highdicom.sr.VolumeSurface` object as the # A tracking identifier for this measurement group tracking_id = hd.sr.TrackingIdentifier( - identifier='Region0001', - uid=hd.UID(), + identifier='Region0001', + uid=hd.UID(), ) # Define the image region (a point) using frame-of-reference coordinates @@ -404,10 +407,10 @@ This example uses a :class:`highdicom.sr.VolumeSurface` object as the # Construct the measurement group group = hd.sr.VolumetricROIMeasurementsAndQualitativeEvaluations( - referenced_volume_surface=volume_surface, - tracking_identifier=tracking_id, - measurements=[...], - qualitative_evaluations=[...], + referenced_volume_surface=volume_surface, + tracking_identifier=tracking_id, + measurements=[...], + qualitative_evaluations=[...], ) The final example uses an :class:`highdicom.sr.ReferencedSegment` as the @@ -428,22 +431,22 @@ The final example uses an :class:`highdicom.sr.ReferencedSegment` as the # A tracking identifier for this measurement group tracking_id = hd.sr.TrackingIdentifier( - identifier='Region3D0001', - uid=hd.UID(), + identifier='Region3D0001', + uid=hd.UID(), ) # Define the image region using a specific segment from the segmentation ref_segment = hd.sr.ReferencedSegment.from_segmentation( - segmentation=seg, - segment_number=1, + segmentation=seg, + segment_number=1, ) # Construct the measurement group group = hd.sr.VolumetricROIMeasurementsAndQualitativeEvaluations( - referenced_segment=ref_segment, - tracking_identifier=tracking_id, - measurements=[...], - qualitative_evaluations=[...], + referenced_segment=ref_segment, + tracking_identifier=tracking_id, + measurements=[...], + qualitative_evaluations=[...], ) Further Parameters for Measurement Groups @@ -468,6 +471,10 @@ type (some have been omitted for brevity): - ``qualitative_evaluations``: (Sequence of :class:`highdicom.sr.QualitativeEvaluation`, optional) Coded name-value pairs that describe qualitative evaluations, see below. +- ``text_evaluations``: (Sequence of :class:`highdicom.sr.TextEvaluation`, + optional) Name-value pairs with a coded name and a free text value that + describe qualitative evaluations. Use only when the evaluation cannot be + expressed with ``qualitative_evaluations``, see below. - ``finding_category``: (:class:`highdicom.sr.CodedConcept`, optional) Category of observed finding, e.g., anatomic structure or morphologically abnormal structure. @@ -481,7 +488,9 @@ and qualitative evaluations themselves. Information derived from the images or image regions represented by the measurement group may be stored as either measurements, qualitative evaluations, or a mixture or the two. These two concepts play a similar role in the SR, but measurements have numerical values -and qualitative evaluations have categorical values. +and qualitative evaluations have categorical values. As a last resort, a +qualitative evaluation may instead have a free text value, in which case it is +known as a text evaluation in *highdicom*. Qualitative Evaluations ~~~~~~~~~~~~~~~~~~~~~~~ @@ -503,16 +512,141 @@ parameters as coded values: # An evaluation of disease severity as "mild" severity_item = hd.sr.QualitativeEvaluation( - name=codes.SCT.Severity, - value=codes.SCT.Mild, + name=codes.SCT.Severity, + value=codes.SCT.Mild, ) # An evaluation of tumor morphology as adenocarcinoma morphology_item = hd.sr.QualitativeEvaluation( - name=codes.SCT.AssociatedMorphology, - value=codes.SCT.Adenocarcinoma, + name=codes.SCT.AssociatedMorphology, + value=codes.SCT.Adenocarcinoma, + ) + +Optionally, the ``value`` of a Qualitative Evaluation may be further refined +by one or more modifiers, passed as a sequence of +:class:`highdicom.sr.CodeContentItem` objects via the ``modifiers`` parameter. +Modifiers are placed into evaluation item's Content Sequence. +The relevant context groups for modifier names are :dcm:`CID 210 Qualitative +Evaluation Modifier Type ` and for their values +:dcm:`CID 211 Qualitative Evaluation Modifier Value +`. + +.. code-block:: python + + import highdicom as hd + from pydicom.sr.codedict import codes + + # An evaluation of the anatomical structure as the kidney, further + # specified as the posterior part of the left kidney + structure_item = hd.sr.QualitativeEvaluation( + name=codes.SCT.AnatomicalStructure, + value=codes.SCT.Kidney, + modifiers=[ + hd.sr.CodeContentItem( + name=codes.SCT.Laterality, + value=codes.SCT.Left, + ), + hd.sr.CodeContentItem( + name=codes.SCT.TopographicalModifier, + value=codes.SCT.Posterior, + ), + ], + ) + + # Modifiers can be accessed via the "modifiers" property + for modifier in structure_item.modifiers: + print(modifier.name.meaning, modifier.value.meaning) + # Laterality Left + # Topographical modifier Posterior + +.. _tid1500_text_evaluations: + +Text Evaluations +~~~~~~~~~~~~~~~~ + +The standard also allows a qualitative evaluation to have a free text value +instead of a coded one. In *highdicom*, these are represented by the class +:class:`highdicom.sr.TextEvaluation`, which is essentially a single +:class:`highdicom.sr.TextContentItem` within a special template, and they are +passed to measurement groups via the ``text_evaluations`` parameter. + +**You should avoid text evaluations whenever the same information can be +expressed as a coded Qualitative Evaluation.** A large part of the value of a +structured report is that its contents can be interpreted reliably by +software. Free text undermines this: + +- Software receiving the SR cannot reliably interpret free text. Variations in + spelling, abbreviations, phrasing, and language mean that "L kidney", + "left kidney", and "Rein gauche" all describe the same thing, but a + receiving application cannot reliably recognize that. +- Text values cannot be validated against the value sets defined by the + standard, so errors are not caught when the SR is created. +- Text evaluations cannot carry modifiers, so any qualification of the value + has to be expressed in the text too, compounding the problems above. +- Searching and aggregating across many SR documents (e.g. "find all + measurement groups with a moderate severity") is straightforward with codes + and error-prone with text. + +Before reaching for a text evaluation, search for a suitable code (see +:ref:`coding`). + +For example, **do not** do this: + +.. code-block:: python + + import highdicom as hd + from pydicom.sr.codedict import codes + + # Bad: a categorical value stored as free text + severity_item = hd.sr.TextEvaluation( + name=codes.SCT.Severity, + value='mild', ) +when you can do this instead: + +.. code-block:: python + + import highdicom as hd + from pydicom.sr.codedict import codes + + # Good: the same information as a coded value + severity_item = hd.sr.QualitativeEvaluation( + name=codes.SCT.Severity, + value=codes.SCT.Mild, + ) + +Text evaluations are appropriate only when the information is genuinely +unstructured and cannot be enumerated in advance, such as a narrative comment +intended for a human reader. Even then, the *name* of a text evaluation is +always a code, so choose one that describes what kind of text it is: + +.. code-block:: python + + import highdicom as hd + from pydicom.sr.codedict import codes + + # Acceptable: a free text comment for a human reader + comment_item = hd.sr.TextEvaluation( + name=codes.DCM.Comment, + value='Margin poorly visualized due to motion artifact', + ) + + tracking_id = hd.sr.TrackingIdentifier( + identifier='Image0001', + uid=hd.UID(), + ) + + group = hd.sr.MeasurementsAndQualitativeEvaluations( + tracking_identifier=tracking_id, + qualitative_evaluations=[...], + text_evaluations=[comment_item], + ) + +If you find yourself using text evaluations with a small set of values that +recur, that is a strong sign the information is categorical and should be +coded instead. + Measurements (`TID300 `_) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -533,9 +667,9 @@ Here is a basic example: # A volume measurement measurement = hd.sr.Measurement( - name=codes.SCT.Volume, - value=1983.123, - unit=codes.UCUM.CubicMillimeter, + name=codes.SCT.Volume, + value=1983.123, + unit=codes.UCUM.CubicMillimeter, ) In addition, the following optional parameters are available (see the API @@ -603,8 +737,8 @@ highdicom test data within the highdicom repository at # A tracking identifier for this measurement group im_tracking_id = hd.sr.TrackingIdentifier( - identifier='Image0001', - uid=hd.UID(), + identifier='Image0001', + uid=hd.UID(), ) # A measurement using an IBSI code (not in pydicom) @@ -625,25 +759,25 @@ highdicom test data within the highdicom repository at # Construct the measurement group im_group = hd.sr.MeasurementsAndQualitativeEvaluations( - source_images=[source_image], - tracking_identifier=im_tracking_id, - measurements=[hist_measurement], - qualitative_evaluations=[im_evaluation], + source_images=[source_image], + tracking_identifier=im_tracking_id, + measurements=[hist_measurement], + qualitative_evaluations=[im_evaluation], ) # Next, we define a planar ROI measurement group describing a lung nodule # A tracking identifier for this measurement group lung_nodule_roi_tracking_id = hd.sr.TrackingIdentifier( - identifier='LungNodule0001', - uid=hd.UID(), + identifier='LungNodule0001', + uid=hd.UID(), ) # Define the image region (a circle) using image coordinates region = hd.sr.ImageRegion( - graphic_type=hd.sr.GraphicTypeValues.CIRCLE, - graphic_data=np.array([[45.0, 55.0], [45.0, 65.0]]), - source_image=hd.sr.SourceImageForRegion.from_source_image(im), + graphic_type=hd.sr.GraphicTypeValues.CIRCLE, + graphic_data=np.array([[45.0, 55.0], [45.0, 65.0]]), + source_image=hd.sr.SourceImageForRegion.from_source_image(im), ) nodule_measurement = hd.sr.Measurement( name=codes.SCT.Diameter, @@ -657,13 +791,13 @@ highdicom test data within the highdicom repository at # Construct the measurement group planar_group_1 = hd.sr.PlanarROIMeasurementsAndQualitativeEvaluations( - referenced_region=region, - tracking_identifier=lung_nodule_roi_tracking_id, - finding_type=codes.SCT.Nodule, - finding_category=codes.SCT.MorphologicallyAbnormalStructure, - finding_sites=[hd.sr.FindingSite(codes.SCT.Lung)], - measurements=[nodule_measurement], - qualitative_evaluations=[nodule_evaluation], + referenced_region=region, + tracking_identifier=lung_nodule_roi_tracking_id, + finding_type=codes.SCT.Nodule, + finding_category=codes.SCT.MorphologicallyAbnormalStructure, + finding_sites=[hd.sr.FindingSite(codes.SCT.Lung)], + measurements=[nodule_measurement], + qualitative_evaluations=[nodule_evaluation], ) # Next, we define a second planar ROI measurement group describing the @@ -671,15 +805,15 @@ highdicom test data within the highdicom repository at # A tracking identifier for this measurement group aorta_roi_tracking_id = hd.sr.TrackingIdentifier( - identifier='Aorta0001', - uid=hd.UID(), + identifier='Aorta0001', + uid=hd.UID(), ) # Define the image region (a circle) using image coordinates region = hd.sr.ImageRegion( - graphic_type=hd.sr.GraphicTypeValues.POLYLINE, - graphic_data=np.array([[25.0, 45.0], [45.0, 45.0], [45.0, 65.0], [25.0, 65.0]]), - source_image=hd.sr.SourceImageForRegion.from_source_image(im), + graphic_type=hd.sr.GraphicTypeValues.POLYLINE, + graphic_data=np.array([[25.0, 45.0], [45.0, 45.0], [45.0, 65.0], [25.0, 65.0]]), + source_image=hd.sr.SourceImageForRegion.from_source_image(im), ) aorta_measurement = hd.sr.Measurement( name=codes.SCT.Diameter, @@ -689,11 +823,11 @@ highdicom test data within the highdicom repository at # Construct the measurement group planar_group_2 = hd.sr.PlanarROIMeasurementsAndQualitativeEvaluations( - referenced_region=region, - tracking_identifier=aorta_roi_tracking_id, - finding_type=codes.SCT.Aorta, - finding_category=codes.SCT.AnatomicalStructure, - measurements=[aorta_measurement], + referenced_region=region, + tracking_identifier=aorta_roi_tracking_id, + finding_type=codes.SCT.Aorta, + finding_category=codes.SCT.AnatomicalStructure, + measurements=[aorta_measurement], ) # Finally, we define a volumetric ROI measurement group describing a @@ -701,8 +835,8 @@ highdicom test data within the highdicom repository at # A tracking identifier for this measurement group volumetric_roi_tracking_id = hd.sr.TrackingIdentifier( - identifier='Vertebra0001', - uid=hd.UID(), + identifier='Vertebra0001', + uid=hd.UID(), ) # Define the region (a point) using frame of reference coordinates @@ -720,11 +854,11 @@ highdicom test data within the highdicom repository at # Construct the measurement group vol_group = hd.sr.VolumetricROIMeasurementsAndQualitativeEvaluations( - referenced_volume_surface=volume_surface, - tracking_identifier=volumetric_roi_tracking_id, - finding_category=codes.SCT.AnatomicalStructure, - finding_type=codes.SCT.Vertebra, - measurements=[vol_measurement], + referenced_volume_surface=volume_surface, + tracking_identifier=volumetric_roi_tracking_id, + finding_category=codes.SCT.AnatomicalStructure, + finding_type=codes.SCT.Vertebra, + measurements=[vol_measurement], ) measurement_report = hd.sr.MeasurementReport( diff --git a/docs/tid1500parsing.rst b/docs/tid1500parsing.rst index c1082e42d..dcbdfaf84 100644 --- a/docs/tid1500parsing.rst +++ b/docs/tid1500parsing.rst @@ -315,7 +315,9 @@ Searching for Evaluations In addition to numerical measurements, measurement groups may also contain "Qualitative Evaluations". These contain an evaluation of the image represented -using a coded concept. +using a coded concept. Measurement groups may also contain evaluations with +free text values, which *highdicom* calls "Text Evaluations" (see +`Searching for Text Evaluations`_ below). Similar to measurements, you can search for evaluations with the ``get_qualitative_evaluations()`` method. You can optionally filter by name @@ -343,3 +345,48 @@ evaluations with the ``name`` and ``value`` properties. # Access the evaluation's value assert evaluation.value == codes.SCT.NotSignificant + +If a qualitative evaluation has modifiers that further refine its value, these +are available as a list of :class:`highdicom.sr.CodeContentItem` objects via +the ``modifiers`` property (which returns an empty list if there are none). + +Searching for Text Evaluations +------------------------------ + +Evaluations with a free text value (TEXT content items with relationship type +CONTAINS within the measurement group) are not returned by +``get_qualitative_evaluations()``. Instead, use the ``get_text_evaluations()`` +method, which returns a list of :class:`highdicom.sr.TextEvaluation` objects +and may likewise be filtered by name with the ``name`` parameter. Other text +content items in the measurement group, such as the tracking identifier, are +not considered to be text evaluations and are not returned by this method. + +The ``name`` property of a text evaluation returns a +:class:`highdicom.sr.CodedConcept` and the ``value`` property returns a +``str``. + +.. code-block:: python + + import highdicom as hd + from pydicom.sr.codedict import codes + + # Use the same example file in the highdicom test data + sr = hd.sr.srread("data/test_files/sr_document_with_multiple_groups.dcm") + + # Use the first planar measurement group as an example + group = sr.content.get_planar_roi_measurement_groups()[0] + + # Get a list of all text evaluations in the group + text_evaluations = group.get_text_evaluations() + + # Get a list of text evaluations with the name "Comment" + comments = group.get_text_evaluations(name=codes.DCM.Comment) + + for evaluation in comments: + print(evaluation.name.meaning, evaluation.value) + + # This example file contains no text evaluations + assert len(text_evaluations) == 0 + +Since the values are free text, they are generally intended for human readers, +and you should be cautious about attempting to interpret them automatically. diff --git a/pyproject.toml b/pyproject.toml index 770d43c15..7c30aebfd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "highdicom" -version = "0.28.2" +version = "0.29.0" description = "High-level DICOM abstractions." readme = "README.md" requires-python = ">=3.10" diff --git a/src/highdicom/__init__.py b/src/highdicom/__init__.py index 29e6f82f1..34da95a74 100644 --- a/src/highdicom/__init__.py +++ b/src/highdicom/__init__.py @@ -13,6 +13,7 @@ ) from highdicom.content import ( AlgorithmIdentificationSequence, + AnatomicRegion, ContentCreatorIdentificationCodeSequence, IssuerOfIdentifier, LUT, @@ -25,6 +26,7 @@ PlanePositionSequence, PresentationLUT, PresentationLUTTransformation, + PrimaryAnatomicStructure, ReferencedImageSequence, SegmentedPaletteColorLUT, SpecimenCollection, @@ -84,6 +86,7 @@ __all__ = [ 'AlgorithmIdentificationSequence', 'AnatomicalOrientationTypeValues', + 'AnatomicRegion', 'AxisHandedness', 'ChannelDescriptor', 'ContentCreatorIdentificationCodeSequence', @@ -115,6 +118,7 @@ 'PresentationLUT', 'PresentationLUTShapeValues', 'PresentationLUTTransformation', + 'PrimaryAnatomicStructure', 'RGBColorChannels', 'RGB_COLOR_CHANNEL_DESCRIPTOR', 'ReferencedImageSequence', diff --git a/src/highdicom/ann/__init__.py b/src/highdicom/ann/__init__.py index 18b5a6e12..a59223783 100644 --- a/src/highdicom/ann/__init__.py +++ b/src/highdicom/ann/__init__.py @@ -1,5 +1,9 @@ """Package for creation of Annotation (ANN) instances.""" -from highdicom.ann.content import Measurements, AnnotationGroup +from highdicom.ann.content import ( + AnnotatedPropertyType, + AnnotationGroup, + Measurements, +) from highdicom.ann.enum import ( AnnotationCoordinateTypeValues, AnnotationGroupGenerationTypeValues, @@ -13,6 +17,7 @@ } __all__ = [ + 'AnnotatedPropertyType', 'AnnotationCoordinateTypeValues', 'AnnotationGroup', 'AnnotationGroupGenerationTypeValues', diff --git a/src/highdicom/ann/content.py b/src/highdicom/ann/content.py index 3eb50d1b8..9edc43d1f 100644 --- a/src/highdicom/ann/content.py +++ b/src/highdicom/ann/content.py @@ -14,8 +14,12 @@ GraphicTypeValues, ) from highdicom.color import CIELabColor -from highdicom.content import AlgorithmIdentificationSequence -from highdicom.sr.coding import CodedConcept +from highdicom.content import ( + AlgorithmIdentificationSequence, + AnatomicRegion, + PrimaryAnatomicStructure, +) +from highdicom.sr.coding import CodedConcept, _ModifiedCodedConcept from highdicom.uid import UID from highdicom._standard_utils import check_required_attributes @@ -171,6 +175,21 @@ def from_dataset( return cast(Self, measurements) +class AnnotatedPropertyType(_ModifiedCodedConcept): + """Dataset describing the property that an annotation group represents. + + This class may be used instead of a plain + :class:`highdicom.sr.CodedConcept` in order to include modifier codes that + describe characteristics of the annotated property. + + See :dcm:`CID 8135 ` "Microscopy Annotation + Property Types" for the appropriate context group for the root concept. + No context group is defined for modifier codes. + + """ + _MODIFIER_SEQUENCE_NAME = "AnnotationPropertyTypeModifierCodeSequence" + + class AnnotationGroup(Dataset): """Dataset describing a group of annotations.""" @@ -181,7 +200,7 @@ def __init__( uid: str, label: str, annotated_property_category: Code | CodedConcept, - annotated_property_type: Code | CodedConcept, + annotated_property_type: Code | CodedConcept | AnnotatedPropertyType, graphic_type: str | GraphicTypeValues, graphic_data: Sequence[np.ndarray], algorithm_type: str | AnnotationGroupGenerationTypeValues, @@ -191,10 +210,10 @@ def __init__( measurements: Sequence[Measurements] | None = None, description: str | None = None, anatomic_regions: None | ( - Sequence[Code | CodedConcept] + Sequence[Code | CodedConcept | AnatomicRegion] ) = None, primary_anatomic_structures: None | ( - Sequence[Code | CodedConcept] + Sequence[Code | CodedConcept | PrimaryAnatomicStructure] ) = None, display_color: CIELabColor | None = None, ): @@ -213,11 +232,13 @@ def __init__( ``Code("49755003", "SCT", "Morphologically Abnormal Structure")`` (see :dcm:`CID 7150 ` "Segmentation Property Categories") - annotated_property_type: Union[pydicom.sr.coding.Code, highdicom.sr.CodedConcept] + annotated_property_type: Union[pydicom.sr.coding.Code, highdicom.sr.CodedConcept, highdicom.ann.AnnotatedPropertyType] Property the annotated regions of interest represents, e.g., ``Code("108369006", "SCT", "Neoplasm")`` (see :dcm:`CID 8135 ` - "Microscopy Annotation Property Types") + "Microscopy Annotation Property Types"). Use a + :class:`highdicom.ann.AnnotatedPropertyType` to additionally + specify modifier codes, such as laterality. graphic_type: Union[str, highdicom.ann.GraphicTypeValues] Graphic type of annotated regions of interest graphic_data: Sequence[numpy.ndarray] @@ -235,11 +256,14 @@ def __init__( interest description: Union[str, None], optional Description of the annotation group - anatomic_regions: Union[Sequence[Union[pydicom.sr.coding.Code, highdicom.sr.CodedConcept]], None], optional - Anatomic region(s) into which annotations fall - primary_anatomic_structures: Union[Sequence[Union[highdicom.sr.Code, highdicom.sr.CodedConcept]], None], optional + anatomic_regions: Union[Sequence[Union[pydicom.sr.coding.Code, highdicom.sr.CodedConcept, highdicom.AnatomicRegion]], None], optional + Anatomic region(s) into which annotations fall. Use + :class:`highdicom.AnatomicRegion` to include modifier codes. + primary_anatomic_structures: Union[Sequence[Union[pydicom.sr.coding.Code, highdicom.sr.CodedConcept, highdicom.PrimaryAnatomicStructure]], None], optional Anatomic structure(s) the annotations represent - (see CIDs for domain-specific primary anatomic structures) + (see CIDs for domain-specific primary anatomic structures). Use + :class:`highdicom.PrimaryAnatomicStructure` to include modifier + codes. display_color: Union[highdicom.color.CIELabColor, None], optional A recommended color to render this annotation group. @@ -276,6 +300,11 @@ def __init__( self.AnnotationGroupAlgorithmIdentificationSequence = \ algorithm_identification + if isinstance(annotated_property_category, _ModifiedCodedConcept): + raise TypeError( + "Argument 'annotated_property_category' should not have " + f"type {annotated_property_category.__class__.__name__}." + ) if isinstance(annotated_property_category, Code): self.AnnotationPropertyCategoryCodeSequence = [ CodedConcept.from_code(annotated_property_category) @@ -284,14 +313,20 @@ def __init__( self.AnnotationPropertyCategoryCodeSequence = [ annotated_property_category, ] - if isinstance(annotated_property_type, Code): - self.AnnotationPropertyTypeCodeSequence = [ - CodedConcept.from_code(annotated_property_type), - ] - else: - self.AnnotationPropertyTypeCodeSequence = [ - annotated_property_type, - ] + + if ( + isinstance(annotated_property_type, _ModifiedCodedConcept) and not + isinstance(annotated_property_type, AnnotatedPropertyType) + ): + raise TypeError( + "Argument 'annotated_property_type' should not have " + f"type {annotated_property_type.__class__.__name__}." + ) + if not isinstance(annotated_property_type, AnnotatedPropertyType): + annotated_property_type = AnnotatedPropertyType( + annotated_property_type + ) + self.AnnotationPropertyTypeCodeSequence = [annotated_property_type] self.NumberOfAnnotations = len(graphic_data) graphic_type = GraphicTypeValues(graphic_type) @@ -444,15 +479,36 @@ def __init__( self.MeasurementsSequence.append(item) if anatomic_regions is not None: - self.AnatomicRegionSequence = [ - CodedConcept.from_code(region) - for region in anatomic_regions - ] + checked_regions = [] + for region in anatomic_regions: + if ( + isinstance(region, _ModifiedCodedConcept) and not + isinstance(region, AnatomicRegion) + ): + raise TypeError( + "Items of 'anatomic_regions' should not have " + f"type {region.__class__.__name__}." + ) + checked_regions.append(AnatomicRegion.from_code(region)) + + self.AnatomicRegionSequence = checked_regions + if primary_anatomic_structures is not None: - self.PrimaryAnatomicStructureSequence = [ - CodedConcept.from_code(structure) - for structure in primary_anatomic_structures - ] + checked_structures = [] + for structure in primary_anatomic_structures: + if ( + isinstance(structure, _ModifiedCodedConcept) and not + isinstance(structure, PrimaryAnatomicStructure) + ): + raise TypeError( + "Items of 'primary_anatomic_structures' should not " + f"have type {structure.__class__.__name__}." + ) + checked_structures.append( + PrimaryAnatomicStructure.from_code(structure) + ) + + self.PrimaryAnatomicStructureSequence = checked_structures @property def label(self) -> str: @@ -480,8 +536,9 @@ def annotated_property_category(self) -> CodedConcept: return self.AnnotationPropertyCategoryCodeSequence[0] @property - def annotated_property_type(self) -> CodedConcept: - """highdicom.sr.CodedConcept: coded annotated property type""" + def annotated_property_type(self) -> AnnotatedPropertyType: + """highdicom.ann.AnnotatedPropertyType: coded annotated property type + """ return self.AnnotationPropertyTypeCodeSequence[0] @property @@ -504,8 +561,8 @@ def algorithm_identification( return None @property - def anatomic_regions(self) -> list[CodedConcept]: - """List[highdicom.sr.CodedConcept]: + def anatomic_regions(self) -> list[AnatomicRegion]: + """List[highdicom.AnatomicRegion]: List of anatomic regions into which the annotations fall. May be empty. @@ -515,8 +572,8 @@ def anatomic_regions(self) -> list[CodedConcept]: return list(self.AnatomicRegionSequence) @property - def primary_anatomic_structures(self) -> list[CodedConcept]: - """List[highdicom.sr.CodedConcept]: + def primary_anatomic_structures(self) -> list[PrimaryAnatomicStructure]: + """List[highdicom.PrimaryAnatomicStructure]: List of anatomic structures the annotations represent. May be empty. @@ -827,7 +884,7 @@ def from_dataset( ) ] group.AnnotationPropertyTypeCodeSequence = [ - CodedConcept.from_dataset( + AnnotatedPropertyType.from_dataset( group.AnnotationPropertyTypeCodeSequence[0], copy=copy, ) @@ -845,12 +902,12 @@ def from_dataset( ] if hasattr(group, 'AnatomicRegionSequence'): group.AnatomicRegionSequence = [ - CodedConcept.from_dataset(ds, copy=copy) + AnatomicRegion.from_dataset(ds, copy=copy) for ds in group.AnatomicRegionSequence ] if hasattr(group, 'PrimaryAnatomicStructureSequence'): group.PrimaryAnatomicStructureSequence = [ - CodedConcept.from_dataset(ds, copy=copy) + PrimaryAnatomicStructure.from_dataset(ds, copy=copy) for ds in group.PrimaryAnatomicStructureSequence ] diff --git a/src/highdicom/ann/sop.py b/src/highdicom/ann/sop.py index d148b1992..42733ca6d 100644 --- a/src/highdicom/ann/sop.py +++ b/src/highdicom/ann/sop.py @@ -27,7 +27,7 @@ GraphicTypeValues, PixelOriginInterpretationValues, ) -from highdicom.ann.content import AnnotationGroup +from highdicom.ann.content import AnnotatedPropertyType, AnnotationGroup from highdicom.content import ( _add_content_information, ContentCreatorIdentificationCodeSequence, @@ -35,7 +35,7 @@ from highdicom.base import SOPClass, _check_little_endian from highdicom.base_content import ContributingEquipment from highdicom.io import _wrapped_dcmread -from highdicom.sr.coding import CodedConcept +from highdicom.sr.coding import CodedConcept, codes_equal class MicroscopyBulkSimpleAnnotations(SOPClass): @@ -170,17 +170,6 @@ def __init__( sop_class_uid='1.2.840.10008.5.1.4.1.1.91.1', modality='ANN', transfer_syntax_uid=transfer_syntax_uid, - patient_id=src_img.PatientID, - patient_name=src_img.PatientName, - patient_birth_date=src_img.PatientBirthDate, - patient_sex=src_img.PatientSex, - accession_number=src_img.AccessionNumber, - study_id=src_img.StudyID, - study_date=src_img.StudyDate, - study_time=src_img.StudyTime, - referring_physician_name=getattr( - src_img, 'ReferringPhysicianName', None - ), manufacturer=manufacturer, manufacturer_model_name=manufacturer_model_name, device_serial_number=device_serial_number, @@ -327,7 +316,9 @@ def get_annotation_group( def get_annotation_groups( self, annotated_property_category: Code | CodedConcept | None = None, - annotated_property_type: Code | CodedConcept | None = None, + annotated_property_type: ( + Code | CodedConcept | AnnotatedPropertyType | None + ) = None, label: str | None = None, graphic_type: str | GraphicTypeValues | None = None, algorithm_type: None | ( @@ -344,8 +335,17 @@ def get_annotation_groups( annotated_property_category: Union[Code, CodedConcept, None], optional Category of annotated property (e.g., ``codes.SCT.MorphologicAbnormality``) - annotated_property_type: Union[Code, CodedConcept, None], optional - Type of annotated property (e.g., ``codes.SCT.Neoplasm``) + annotated_property_type: Union[Code, CodedConcept, highdicom.ann.AnnotatedPropertyType, None], optional + Type of annotated property (e.g., ``codes.SCT.Neoplasm``). If a + :class:`highdicom.ann.AnnotatedPropertyType` is provided, a group + matches only if its annotated property type has the same root code + *and* exactly the same set of modifier codes (in any order). An + ``AnnotatedPropertyType`` without modifiers therefore matches only + groups whose type has no modifiers. If a plain + :class:`pydicom.sr.coding.Code` or + :class:`highdicom.sr.CodedConcept` is provided, only the root + (unmodified) code is compared and any modifiers on the group's + type are ignored. label: Union[str, None], optional Annotation group label graphic_type: Union[str, GraphicTypeValues, None], optional @@ -382,9 +382,13 @@ def get_annotation_groups( matches.append(is_match) if annotated_property_type is not None: - is_match = eq( + is_match = codes_equal( item.annotated_property_type, - annotated_property_type + annotated_property_type, + ignore_modifiers=not isinstance( + annotated_property_type, + AnnotatedPropertyType, + ), ) matches.append(is_match) diff --git a/src/highdicom/base.py b/src/highdicom/base.py index 5f8408eb8..a202251b4 100644 --- a/src/highdicom/base.py +++ b/src/highdicom/base.py @@ -123,7 +123,7 @@ def __init__( Name of the referring physician content_qualification: Union[str, highdicom.ContentQualificationValues, None], optional Indicator of content qualification - coding_schemes: Union[Sequence[highdicom.sr.CodingSchemeIdentificationItem], None], optional + coding_schemes: Union[Sequence[highdicom.coding_schemes.CodingSchemeIdentificationItem], None], optional private or public coding schemes that are not part of the DICOM standard series_description: Union[str, None], optional @@ -334,14 +334,15 @@ def __init__( ) self.ContentQualification = content_qualification.value if coding_schemes is not None: - self.CodingSchemeIdentificationSequence: list[Dataset] = [] for item in coding_schemes: if not isinstance(item, CodingSchemeIdentificationItem): raise TypeError( 'Coding scheme identification item must have type ' '"CodingSchemeIdentificationItem".' ) - self.CodingSchemeIdentificationSequence.append(item) + + if len(coding_schemes) > 0: + self.CodingSchemeIdentificationSequence = list(coding_schemes) @property def transfer_syntax_uid(self) -> UID: diff --git a/src/highdicom/coding_schemes.py b/src/highdicom/coding_schemes.py index c54fce2e9..00354213f 100644 --- a/src/highdicom/coding_schemes.py +++ b/src/highdicom/coding_schemes.py @@ -2,26 +2,32 @@ from pydicom.dataset import Dataset +from highdicom.enum import CodingSchemeURLTypeValues + class CodingSchemeResourceItem(Dataset): """Class for items of the Coding Scheme Resource Sequence.""" - def __init__(self, url: str, url_type: str) -> None: + def __init__( + self, + url: str, + url_type: CodingSchemeURLTypeValues | str, + ) -> None: """ Parameters ---------- url: str - unique resource locator - url_type: str - type of resource `url` points to (options: `{"DOC", "OWL", "CSV"}`) + Unique resource locator + url_type: highdicom.CodingSchemeURLTypeValues | str + Type of resource `url` points to. """ super().__init__() self.CodingSchemeURL = str(url) - if url_type not in {"DOC", "OWL", "CSV"}: - raise ValueError('Unknonw URL type.') - self.CodingSchemeURLType = str(url_type) + self.CodingSchemeURLType = CodingSchemeURLTypeValues( + url_type + ).value class CodingSchemeIdentificationItem(Dataset): diff --git a/src/highdicom/color.py b/src/highdicom/color.py index 364b5d3c5..4aec0921a 100644 --- a/src/highdicom/color.py +++ b/src/highdicom/color.py @@ -19,12 +19,28 @@ logger = logging.getLogger(__name__) +# White points, defined by their 4-figure CIE x,y chromaticities, as in the +# sample code of the CSS Color Module Level 4 +# (https://www.w3.org/TR/css-color-4/#color-conversion-code). +# +# DICOM encodes CIELab values in the same way as the ICC Profile Connection +# Space (PCS, see PS3.3 C.10.7.1.1), i.e. relative to the D50 illuminant, +# whereas the native white point of sRGB is D65. The conversions below +# therefore chromatically adapt between the two using the linear Bradford +# transform. Note that for neutral (gray) colors the results are the same +# either way, for chromatic colors the a* and b* values differ slightly. +_D50_WHITEPOINT_X = 0.3457 / 0.3585 +_D50_WHITEPOINT_Y = 1.0 +_D50_WHITEPOINT_Z = (1.0 - 0.3457 - 0.3585) / 0.3585 + + def _rgb_to_xyz(r: float, g: float, b: float) -> tuple[float, float, float]: - """Convert an RGB color to CIE XYZ representation. + """Convert an sRGB color to CIE XYZ representation. - Outputs are scaled between 0.0 and the white point (95.05, 100.0, 108.89). - As a private function, no checks are performed that input values are valid, - and output values are not clipped. + Outputs are relative to the D50 white point (ICC PCS XYZ) and scaled + between 0.0 and the white point (0.9642, 1.0, 0.8251). As a private + function, no checks are performed that input values are valid, and output + values are not clipped. Parameters ---------- @@ -38,47 +54,79 @@ def _rgb_to_xyz(r: float, g: float, b: float) -> tuple[float, float, float]: Returns ------- x: float - X component as a float between 0.0 and 95.05. + X component as a float between 0.0 and 0.9642. y: float - Y component as a float between 0.0 and 100.0. + Y component as a float between 0.0 and 1.0. z: float - Z component as a float between 0.0 and 108.89. + Z component as a float between 0.0 and 0.8251. """ - # Adapted from ColorUtilities module of pixelmed: - # https://www.dclunie.com/pixelmed/software/javadoc/com/pixelmed/utils/ColorUtilities.html - def convert_component(c: float) -> float: + # Matches the implementation of DCMTK's IODCIELabUtil::rgb2Xyz() + def invert_gamma(c: float) -> float: + # sRGB transfer function (IEC 61966-2-1), gamma-encoded to linear c = c / 255.0 if c > 0.04045: return ((c + 0.055) / 1.055) ** 2.4 return c / 12.92 - r = convert_component(r) * 100 - g = convert_component(g) * 100 - b = convert_component(b) * 100 - - x = r * 0.4124 + g * 0.3576 + b * 0.1805 - y = r * 0.2126 + g * 0.7152 + b * 0.0722 - z = r * 0.0193 + g * 0.1192 + b * 0.9505 + r = invert_gamma(r) + g = invert_gamma(g) + b = invert_gamma(b) + + # Linear RGB to CIE XYZ (D65) + x65 = ( + (506752.0 / 1228815.0) * r + + (87881.0 / 245763.0) * g + + (12673.0 / 70218.0) * b + ) + y65 = ( + (87098.0 / 409605.0) * r + + (175762.0 / 245763.0) * g + + (12673.0 / 175545.0) * b + ) + z65 = ( + (7918.0 / 409605.0) * r + + (87881.0 / 737289.0) * g + + (1001167.0 / 1053270.0) * b + ) + + # Chromatic adaptation from D65 to D50 (linear Bradford) + x = ( + 1.0479297925449969 * x65 + + 0.022946870601609652 * y65 - + 0.05019226628920524 * z65 + ) + y = ( + 0.02962780877005599 * x65 + + 0.9904344267538799 * y65 - + 0.017073799063418826 * z65 + ) + z = ( + -0.009243040646204504 * x65 + + 0.015055191490298152 * y65 + + 0.7518742814281371 * z65 + ) return x, y, z def _xyz_to_rgb(x: float, y: float, z: float) -> tuple[float, float, float]: - """Convert a CIE XYZ color to RGB representation. + """Convert a CIE XYZ color to sRGB representation. - Inputs are scaled between 0.0 and the white point (95.05, 100.0, 108.89). - As a private function, no checks are performed that input values are valid, - and output values are not clipped. + Inputs are relative to the D50 white point (ICC PCS XYZ) and scaled + between 0.0 and the white point (0.9642, 1.0, 0.8251). As a private + function, no checks are performed that input values are valid, and output + values are not clipped. Consequently colors that lie outside the sRGB + gamut give values outside the 0.0 to 255.0 range. Parameters ---------- x: float - X component as a float between 0.0 and 95.05. + X component as a float between 0.0 and 0.9642. y: float - Y component as a float between 0.0 and 100.0. + Y component as a float between 0.0 and 1.0. z: float - Z component as a float between 0.0 and 108.89. + Z component as a float between 0.0 and 0.8251. Returns ------- @@ -90,42 +138,67 @@ def _xyz_to_rgb(x: float, y: float, z: float) -> tuple[float, float, float]: Blue component between 0.0 and 255.0 (inclusive). """ - # Adapted from ColorUtilities module of pixelmed: - # https://www.dclunie.com/pixelmed/software/javadoc/com/pixelmed/utils/ColorUtilities.html - x = x / 100 - y = y / 100 - z = z / 100 - - r = x * 3.2406 + y * -1.5372 + z * -0.4986 - g = x * -0.9689 + y * 1.8758 + z * 0.0415 - b = x * 0.0557 + y * -0.2040 + z * 1.0570 - - def convert_component(c: float) -> float: + # Matches the implementation of DCMTK's IODCIELabUtil::xyz2Rgb(), except + # that out-of-gamut values are not clipped here (this is left to the + # caller, which may instead want to report them as out of gamut) + # Chromatic adaptation from D50 to D65 (linear Bradford) + x65 = ( + 0.955473421488075 * x - + 0.02309845494876471 * y + + 0.06325924320057072 * z + ) + y65 = ( + -0.0283697093338637 * x + + 1.0099953980813041 * y + + 0.021041441191917323 * z + ) + z65 = ( + 0.012314014864481998 * x - + 0.020507649298898964 * y + + 1.330365926242124 * z + ) + + # CIE XYZ (D65) to linear RGB + r = ( + (12831.0 / 3959.0) * x65 - + (329.0 / 214.0) * y65 - + (1974.0 / 3959.0) * z65 + ) + g = ( + (-851781.0 / 878810.0) * x65 + + (1648619.0 / 878810.0) * y65 + + (36519.0 / 878810.0) * z65 + ) + b = ( + (705.0 / 12673.0) * x65 - + (2585.0 / 12673.0) * y65 + + (705.0 / 667.0) * z65 + ) + + def apply_gamma(c: float) -> float: + # sRGB transfer function (IEC 61966-2-1), linear to gamma-encoded if c > 0.0031308: - return 1.055 * (c ** (1 / 2.4)) - 0.055 + return 1.055 * (c ** (1.0 / 2.4)) - 0.055 return 12.92 * c - r = convert_component(r) * 255 - g = convert_component(g) * 255 - b = convert_component(b) * 255 - - return r, g, b + return apply_gamma(r) * 255, apply_gamma(g) * 255, apply_gamma(b) * 255 def _xyz_to_lab(x: float, y: float, z: float) -> tuple[float, float, float]: """Convert a CIE XYZ color to CIE Lab representation. - As a private function, no checks are performed that input values are valid, - and output values are not clipped. + Both input and output are relative to the D50 white point (ICC PCS). As a + private function, no checks are performed that input values are valid, and + output values are not clipped. Parameters ---------- x: float - X component. + X component as a float between 0.0 and 0.9642. y: float - Y component. + Y component as a float between 0.0 and 1.0. z: float - Z component. + Z component as a float between 0.0 and 0.8251. Returns ------- @@ -137,16 +210,16 @@ def _xyz_to_lab(x: float, y: float, z: float) -> tuple[float, float, float]: Blue-yellow value from -128.0 (blue) to 127.0 (yellow). """ - # Adapted from ColorUtilities module of pixelmed: - # https://www.dclunie.com/pixelmed/software/javadoc/com/pixelmed/utils/ColorUtilities.html - x = x / 95.047 - y = y / 100.0 - z = z / 108.883 + # Matches the implementation of DCMTK's IODCIELabUtil::xyz2Lab() + x = x / _D50_WHITEPOINT_X + y = y / _D50_WHITEPOINT_Y + z = z / _D50_WHITEPOINT_Z def convert_component(c: float) -> float: - if c >= 8.85645167903563082e-3: - return c ** (1.0 / 3) - return (841.0 / 108.0) * c + (4.0 / 29.0) + # epsilon = (6/29)^3 = 216/24389, kappa = (29/3)^3 = 24389/27 + if c > 216.0 / 24389.0: + return c ** (1.0 / 3.0) + return ((24389.0 / 27.0) * c + 16.0) / 116.0 x = convert_component(x) y = convert_component(y) @@ -166,9 +239,10 @@ def _lab_to_xyz( ) -> tuple[float, float, float]: """Convert a CIE Lab color to CIE XYZ representation. - Outputs are scaled between 0.0 and the white point (95.05, 100.0, 108.89). - As a private function, no checks are performed that input values are valid, - and output values are not clipped. + Both input and output are relative to the D50 white point (ICC PCS). + Outputs are scaled between 0.0 and the white point (0.9642, 1.0, 0.8251). + As a private function, no checks are performed that input values are + valid, and output values are not clipped. Parameters ---------- @@ -182,42 +256,37 @@ def _lab_to_xyz( Returns ------- x: float - X component. + X component as a float between 0.0 and 0.9642. y: float - Y component. + Y component as a float between 0.0 and 1.0. z: float - Z component. + Z component as a float between 0.0 and 0.8251. """ - # Adapted from ColorUtilities module of pixelmed: - # https://www.dclunie.com/pixelmed/software/javadoc/com/pixelmed/utils/ColorUtilities.html + # Matches the implementation of DCMTK's IODCIELabUtil::lab2Xyz() y = (l_star + 16) / 116 x = a_star / 500 + y z = y - b_star / 200 def convert_component(c: float) -> float: - c3 = c ** 3 - - if c3 > 0.008856: - return c3 - return (c - 16.0 / 116) / 7.787 - - x = convert_component(x) - y = convert_component(y) - z = convert_component(z) + # c > 6/29 is equivalent to c ** 3 > epsilon + if c > 6.0 / 29.0: + return c ** 3 + return (116.0 * c - 16.0) / (24389.0 / 27.0) - x = 95.047 * x - y = 100.0 * y - z = 108.883 * z + x = _D50_WHITEPOINT_X * convert_component(x) + y = _D50_WHITEPOINT_Y * convert_component(y) + z = _D50_WHITEPOINT_Z * convert_component(z) return x, y, z def _rgb_to_lab(r: float, g: float, b: float) -> tuple[float, float, float]: - """Convert an RGB color to CIE Lab representation. + """Convert an sRGB color to CIE Lab representation. - As a private function, no checks are performed that input values are valid, - and output values are not clipped. + The output is relative to the D50 white point (ICC PCS), as used by DICOM. + As a private function, no checks are performed that input values are + valid, and output values are not clipped. Parameters ---------- @@ -246,11 +315,12 @@ def _lab_to_rgb( a_star: float, b_star: float, ) -> tuple[float, float, float]: - """Convert a CIE Lab color to RGB representation. + """Convert a CIE Lab color to sRGB representation. - As a private function, no checks are performed that input values are valid, - and output values are not clipped. Lab colors that cannot be represented in - RGB will have values outside to 0.0 to 255.0 range. + The input is relative to the D50 white point (ICC PCS), as used by DICOM. + As a private function, no checks are performed that input values are + valid, and output values are not clipped. Lab colors that cannot be + represented in sRGB will have values outside to 0.0 to 255.0 range. Parameters ---------- @@ -291,7 +361,7 @@ class CIELabColor: >>> >>> color = hd.color.CIELabColor(50.0, 34.0, 12.4) >>> print(color.to_rgb()) - (177, 95, 99) + (175, 94, 100) Construct a CIE-Lab color from an RGB color and examine the Lab components: @@ -299,7 +369,7 @@ class CIELabColor: >>> >>> color = hd.color.CIELabColor.from_rgb(0, 255, 0) >>> print(color.l_star, color.a_star, color.b_star) - 87.73632410162509 -86.1828793774319 83.1828793774319 + 87.81872281986725 -79.27237354085602 80.99610894941634 Construct a CIE-Lab color from the name of a well-known color: @@ -307,7 +377,7 @@ class CIELabColor: >>> >>> color = hd.color.CIELabColor.from_string('turquoise') >>> print(color.l_star, color.a_star, color.b_star) - 81.2664988174258 -44.07782101167315 -4.035019455252922 + 80.96131837949187 -45.13618677042801 -4.680933852140072 Within DICOM files, the three components are represented using scaled and shifted unsigned 16 bit integer values. You can move between these @@ -318,10 +388,10 @@ class CIELabColor: >>> color = hd.color.CIELabColor.from_string('orange') >>> # Print the values that would actually be stored in a DICOM file >>> print(color.value) - (49107, 39048, 53188) + (49538, 39968, 53230) >>> # Create a color directly from these values - >>> color2 = hd.color.CIELabColor.from_dicom_value((49107, 39048, 53188)) - >>>> print(color2.to_rgb()) + >>> color2 = hd.color.CIELabColor.from_dicom_value((49538, 39968, 53230)) + >>> print(color2.to_rgb()) (255, 165, 0) """ diff --git a/src/highdicom/content.py b/src/highdicom/content.py index 9fe864cc3..0ac0f3411 100644 --- a/src/highdicom/content.py +++ b/src/highdicom/content.py @@ -31,7 +31,9 @@ ) from highdicom.pixels import ( _check_rescale_dtype, + _expand_segmented_lut, _get_combined_palette_color_lut, + _get_expanded_lut_length, _parse_palette_color_lut_attributes, _select_voi_lut, _select_voi_window_center_width, @@ -39,7 +41,8 @@ apply_voi_window, ) from highdicom.sr.enum import ValueTypeValues -from highdicom.sr.coding import CodedConcept +from highdicom.sr.coding import CodedConcept, _ModifiedCodedConcept +from highdicom.spatial import _check_image_orientation from highdicom.sr.value_types import ( CodeContentItem, ContentSequence, @@ -62,6 +65,39 @@ ) +class AnatomicRegion(_ModifiedCodedConcept): + """Dataset describing the anatomic region into which an image or annotation + falls. + + This class may be used instead of a plain + :class:`highdicom.sr.CodedConcept` in order to include modifier codes that + describe characteristics of the anatomic, such as laterality. + + See :dcm:`CID 4 ` "Anatomic Region", :dcm:`CID 4031 + ` "Common Anatomic Regions", as as well as other + domain-specific CIDs where this class is used for appropriate context + groups for the root concept, and :dcm:`CID 2 ` + "Anatomic Modifier" for the context group for modifier codes. + + """ + _MODIFIER_SEQUENCE_NAME = "AnatomicRegionModifierSequence" + + +class PrimaryAnatomicStructure(_ModifiedCodedConcept): + """Dataset describing the property a segmentation represents. + + This class may be used instead of a plain + :class:`highdicom.sr.CodedConcept` in order to include modifier codes that + describe characteristics of the segmented property, such as laterality. + + See domain-specific context groups where this class is used for the + appropriate context group and :dcm:`CID 2 ` + "Anatomic Modifier" for the context group for modifier codes. + + """ + _MODIFIER_SEQUENCE_NAME = "PrimaryAnatomicStructureModifierSequence" + + class AlgorithmIdentificationSequence(DataElementSequence): """Sequence of data elements describing information useful for @@ -661,6 +697,7 @@ def __init__( super().__init__() item = Dataset() coordinate_system = CoordinateSystemNames(coordinate_system) + _check_image_orientation(image_orientation) image_orientation_ds = [ DS(io, auto_format=True) for io in image_orientation ] @@ -2997,6 +3034,7 @@ def extract_from_dataset(cls, dataset: Dataset, color: str) -> Self: setattr(new_ds, kw, getattr(dataset, kw)) new_ds.__class__ = cls + new_ds._lut_data = None return cast(Self, new_ds) @@ -3091,54 +3129,7 @@ def __init__( segmented_lut_data.tobytes() ) - expanded_lut_values = [] - i = 0 - offset = 0 - while i < len(segmented_lut_data): - opcode = segmented_lut_data[i] - i += 1 - if opcode == 0: - # Discrete segment type (constant) - length = segmented_lut_data[i] - i += 1 - value = segmented_lut_data[i] - i += 1 - expanded_lut_values.extend([ - value for _ in range(length) - ]) - offset += length - elif opcode == 1: - # Linear segment type (interpolation) - length = segmented_lut_data[i] - i += 1 - start_value = expanded_lut_values[offset - 1] - end_value = segmented_lut_data[i] - i += 1 - step = (end_value - start_value) / (length - 1) - expanded_lut_values.extend([ - start_value + int(np.round(j * step)) - for j in range(length) - - ]) - offset += length - elif opcode == 2: - # TODO - raise ValueError( - 'Indirect segment type is not yet supported for ' - 'Segmented Palette Color Lookup Table.' - ) - else: - raise ValueError( - f'Encountered unexpected segment type {opcode} for ' - 'Segmented Palette Color Lookup Table.' - ) - - self._lut_data = np.array( - expanded_lut_values, - dtype=segmented_lut_data.dtype, - ) - - len_data = len(expanded_lut_values) + len_data = _get_expanded_lut_length(segmented_lut_data) if len_data == 2 ** 16: number_of_entries = 0 else: @@ -3152,7 +3143,6 @@ def __init__( @property def segmented_lut_data(self) -> np.ndarray: """numpy.ndarray: segmented lookup table data""" - length = self.number_of_entries data = getattr(self, f'Segmented{self._attr_name_prefix}Data') if self.bits_per_entry == 8: dtype = np.uint8 @@ -3160,19 +3150,13 @@ def segmented_lut_data(self) -> np.ndarray: dtype = np.uint16 else: raise RuntimeError("Invalid LUT descriptor.") - # The LUT data attributes have VR OW (16-bit other words) - array = np.frombuffer(data, dtype=dtype) - if len(array) != length: - raise RuntimeError( - 'Length of LUTData does not match the value expected from the ' - f'LUTDescriptor. Expected {length}, found {len(array)}.' - ) - return array + + return np.frombuffer(data, dtype=dtype) @property def lut_data(self) -> np.ndarray: """numpy.ndarray: expanded lookup table data""" - return self._lut_data + return _expand_segmented_lut(self.segmented_lut_data) @property def number_of_entries(self) -> int: @@ -3203,6 +3187,37 @@ def bits_per_entry(self) -> int: descriptor = getattr(self, f'{self._attr_name_prefix}Descriptor') return int(descriptor[2]) + def apply( + self, + array: np.ndarray, + dtype: type | str | np.dtype | None = None, + ) -> np.ndarray: + """Apply the LUT to a pixel array. + + Parameters + ---------- + apply: numpy.ndarray + Pixel array to which the LUT should be applied. Can be of any shape + but must have an integer datatype. + dtype: Union[type, str, numpy.dtype, None], optional + Datatype of the output array. If ``None``, an unsigned integer + datatype corresponding to the number of bits in the LUT will be + used (either ``numpy.uint8`` or ``numpy.uint16``). Only safe casts + are permitted. + + Returns + ------- + numpy.ndarray + Array with LUT applied. + + """ + return apply_lut( + array=array, + lut_data=self.lut_data, + first_mapped_value=self.first_mapped_value, + dtype=dtype, + ) + @classmethod def extract_from_dataset(cls, dataset: Dataset, color: str) -> Self: """Construct from an existing dataset. @@ -3647,7 +3662,12 @@ def extract_from_dataset(cls, dataset: Dataset) -> Self: data_kw = f'{color}PaletteColorLookupTableData' setattr(new_dataset, data_kw, data) + uid = dataset.get('PaletteColorLookupTableUID') + if uid is not None: + new_dataset.PaletteColorLookupTableUID = uid + new_dataset.__class__ = cls + new_dataset._lut_data = None return cast(Self, new_dataset) def apply( diff --git a/src/highdicom/enum.py b/src/highdicom/enum.py index 996aeb062..a8e3d828a 100644 --- a/src/highdicom/enum.py +++ b/src/highdicom/enum.py @@ -521,3 +521,22 @@ class PixelDataKeywords(Enum): DOUBLE_FLOAT_PIXEL_DATA = 'DoubleFloatPixelData' """64-bit-float-valued pixel data (Double Floating Point Image Pixel Module).""" # noqa: E501 + + +class CodingSchemeURLTypeValues(Enum): + + """Enumerated values for Coding Scheme URL Type attribute.""" + + DOC = 'DOC' + """The resource is human-readable information describing the scheme.""" + + OWL = 'OWL' + """The resource contains an OWL file representing the scheme.""" + + CSV = 'CSV' + """The resource contains a comma separated value text file representing + the scheme. + """ + + FHIR = 'FHIR' + """The resource is a FHIR CodingScheme.""" diff --git a/src/highdicom/frame.py b/src/highdicom/frame.py index e0af11437..4bf8fe0ab 100644 --- a/src/highdicom/frame.py +++ b/src/highdicom/frame.py @@ -172,7 +172,7 @@ def encode_frame( 'must have a signed integer dtype.' ) else: - if array.dtype.kind != 'u': + if array.dtype.kind not in ('u', 'b'): raise ValueError( 'When encoding frames with pixel_representation=0, array ' 'must have an unsigned integer dtype.' diff --git a/src/highdicom/ko/sop.py b/src/highdicom/ko/sop.py index 5dc17f571..7448d716c 100644 --- a/src/highdicom/ko/sop.py +++ b/src/highdicom/ko/sop.py @@ -119,20 +119,10 @@ def __init__( manufacturer=manufacturer, modality='KO', transfer_syntax_uid=transfer_syntax_uid, - patient_id=evidence[0].PatientID, - patient_name=evidence[0].PatientName, - patient_birth_date=evidence[0].PatientBirthDate, - patient_sex=evidence[0].PatientSex, - accession_number=evidence[0].AccessionNumber, - study_id=evidence[0].StudyID, - study_date=evidence[0].StudyDate, - study_time=evidence[0].StudyTime, - referring_physician_name=getattr( - evidence[0], 'ReferringPhysicianName', None - ), specific_character_set=specific_character_set, **kwargs ) + self.copy_patient_and_study_information(evidence[0]) self._add_contributing_equipment(contributing_equipment) if institution_name is not None: diff --git a/src/highdicom/legacy/__init__.py b/src/highdicom/legacy/__init__.py index b0ed72ed4..fc23144af 100644 --- a/src/highdicom/legacy/__init__.py +++ b/src/highdicom/legacy/__init__.py @@ -7,6 +7,9 @@ LegacyConvertedEnhancedPETImage, lceread, ) +from highdicom.legacy.config import ( + HarmonizationConfig, +) SOP_CLASS_UIDS = { '1.2.840.10008.5.1.4.1.1.4.4', # Legacy Converted Enhanced MR Image @@ -15,6 +18,7 @@ } __all__ = [ + 'HarmonizationConfig', 'LegacyConvertedEnhancedCTImage', 'LegacyConvertedEnhancedMRImage', 'LegacyConvertedEnhancedPETImage', diff --git a/src/highdicom/legacy/config.py b/src/highdicom/legacy/config.py new file mode 100644 index 000000000..f8d88c284 --- /dev/null +++ b/src/highdicom/legacy/config.py @@ -0,0 +1,109 @@ +"""Configuration classes for legacy attribute harmonization.""" +from collections.abc import Callable, Sequence +from inspect import signature + +from pydicom.tag import BaseTag +from pydicom.datadict import keyword_for_tag, tag_for_keyword + + +class HarmonizationConfig: + + """Configuration for harmonizing an attribute. + + """ + + def __init__( + self, + destination_keyword: str, + destination_sequence_keyword: str, + source_tags: Sequence[BaseTag], + private_creator_name: str | None = None, + mapping: Callable | None = None + ) -> None: + """ + + Parameters + ---------- + destination_keyword: str + DICOM keyword of the (standard) attribute that the result will be + placed into. + destination_sequence_keyword: str + DICOM keyword of the (standard) sequence that the resulting + attribute will be placed into. + source_tags: Sequence[pydicom.tag.BaseTag] + List of tags for attributes that are required in the legacy images + in order to determine the value for the destination attribute. Tags + may be either standard (even group number) or private (odd group + number), and the two types may be mixed. However, if any tag is + private, ``private_creator_name`` must be provided and must apply + to all private tags in this list. + private_creator_name: str | None, optional + Name of the private creator of the source attributes, if any are + private. May be omitted if all items of ``source_tags`` are + standard. + mapping: Callable | None, optional + A callable that takes as input a list containing the values of the + attributes defined in ``source_tags``, with order corresponding + between the two lists, and returns the output value for the + destination attribute. If this parameter is ``None`` (the default), + the ``source_tags`` list must contain a single item, and the value + of that attribute is used as-is for placement into the output + attribute. + + """ # noqa: E501 + if tag_for_keyword(destination_keyword) is None: + raise ValueError( + f"{destination_keyword} is not a valid DICOM keyword." + ) + + if len(source_tags) == 0: + raise ValueError( + "'source_tags' may not be empty." + ) + if not all(isinstance(t, BaseTag) for t in source_tags): + raise TypeError( + "Items of 'source_tags' must be of type pydicom.BaseTag" + ) + + # Mask the variable position bits of private tags + source_tags = [ + BaseTag(t & 0xFFFF_00FF) if t.is_private else t + for t in source_tags + ] + + for t in source_tags: + if not t.is_private and keyword_for_tag(t) is None: + raise ValueError(f"Unrecognized standard tag: {t}") + + if ( + private_creator_name is None and + any(t.is_private for t in source_tags) + ): + raise TypeError( + "'private_creator_name' must be specified because one or more " + "tags are private." + ) + + if mapping is None: + if len(source_tags) is not None: + raise TypeError( + "'mapping' must be provided when multiple source tags are " + "specified." + ) + else: + if not isinstance(mapping, Callable): + raise TypeError( + "'mapping' must be a callable object" + ) + + if len(signature(mapping).parameters) != len(source_tags): + raise TypeError( + "Number of parameters taken by 'mapping' must match number " + "of items in 'source_tags'" + ) + + self.destination_keyword = destination_keyword + self.destination_sequence_keyword = destination_sequence_keyword + self.source_tags = source_tags + self.private_creator_name = private_creator_name + self.mapping = mapping diff --git a/src/highdicom/legacy/sop.py b/src/highdicom/legacy/sop.py index d5c1459c6..ebdfd87e2 100644 --- a/src/highdicom/legacy/sop.py +++ b/src/highdicom/legacy/sop.py @@ -46,6 +46,7 @@ from highdicom.enum import PhotometricInterpretationValues from highdicom.frame import encode_frame, get_lossy_compression_attributes from highdicom.image import Image, _Image +from highdicom.legacy.config import HarmonizationConfig from highdicom.spatial import get_series_volume_positions from highdicom.sr import CodedConcept from highdicom.uid import UID as hd_UID @@ -170,6 +171,33 @@ def _istag_group_length(t: BaseTag) -> bool: return t.element == 0 +def _normalize_private_tag(t: BaseTag, ds: Dataset) -> tuple[str, BaseTag]: + """Get a normalized representation of a private tag. + + Parameters + ---------- + t: pydicom.tag.BaseTag + The tag in question + ds: pydicom.Dataset + The dataset that the tag is drawn from. + + Returns + ------- + str: + Private creator name + pydicom.BaseTag: + Normalized version of the tag, removing the variable bits (first two + hex digits in the element part of the tag). + + """ + creator_tag = t.private_creator + if creator_tag not in ds: + creator_name = "UNKNOWN_CREATOR" + else: + creator_name = ds[t.private_creator].value + return creator_name, BaseTag(t & 0xFFFF_00FF) + + def _read_ambiguous_vr(dataset: Dataset, kw: str) -> int: """Read attribute from dataset while coercing ambiguous VR. @@ -190,18 +218,15 @@ def _read_ambiguous_vr(dataset: Dataset, kw: str) -> int: val = getattr(dataset, kw) if ( dataset.PixelRepresentation == 1 and - dataset[kw].VR == "US" + dataset[kw].VR == "US" and + # Value in this range indicates that correction is + # needed, since it is invalid for VR of 'SS' + val > 32767 ): - # Incorrect VR is used - - if val > 32767: - # Value in this range indicates that correction is - # needed, since it is invalid for VR of 'SS' - - # Find the negative number that has the same 16-bit binary - # representation as the value found and assume this is what was - # intended in the original file - return val - 65536 + # Incorrect VR is used - Find the negative number that has the same + # 16-bit binary representation as the value found and assume this is + # what was intended in the original file + return val - 65536 return val @@ -287,6 +312,26 @@ def _get_dimension_index_sequence_item( return index_ds +def _get_allowed_functional_groups( + modality: str, + include_enhanced_groups: bool, +) -> set[str]: + modules = [ + f'legacy-converted-enhanced-{modality}-image-multi-frame-functional-groups' + ] + if include_enhanced_groups: + modules.append(f'enhanced-{modality}-image-multi-frame-functional-groups') + + sequences = set() + for m in modules: + tree = construct_module_tree(m) + sequences.update( + tree['attributes']['PerFrameFunctionalGroupsSequence']['attributes'].keys() + ) + + return sequences + + @dataclass class _AttributeConfig: """Configuration for how to copy an attribute to the converted instance. @@ -342,6 +387,8 @@ def __init__( use_extended_offset_table: bool = False, require_volume: bool = False, include_dimension_index: bool | None = None, + include_enhanced_groups: bool = True, + harmonization_configs: list[HarmonizationConfig] | None = None, strict: bool = False, skip_private_attributes: bool = False, workers: int | Executor = 0, @@ -399,6 +446,17 @@ def __init__( passed with no index. If ``False``, no attempt will be made to sort the datasets, they will be encoded in the order they are passed without including a dimension index. + include_enhanced_groups: bool, optional + Include multi-frame functional groups that are not part of the + Legacy Enhanced IOD, but are part of the corresponding Enhanced + IOD, if information exists in the legacy files to include in them. + If ``False``, only those groups explicitly included in the Legacy + Converted IOD are created in the new file, and any attributes that + do not belong in them are placed into the + UnassignedSharedConvertedAttributesSequence or + UnassignedPerFrameConvertedAttributesSequence. + harmonization_configs: list[highdicom.legacy.config.HarmonizationConfig] | None, optional + Harmonization configs with attributes in this functional group. strict: bool, optional Whether to use strict requirements on the new converted dataset. If True and any attributes required to create a standard-compliant @@ -422,9 +480,32 @@ def __init__( self._use_extended_offset_table = use_extended_offset_table self._keyword_shared_dict: dict[str, bool] = {} self._unused_keywords: set[str] = set() - self._private_tag_shared_dict: dict[BaseTag, bool] + self._private_tag_shared_dict: dict[ + tuple[str, BaseTag], tuple[BaseTag, bool] + ] self._dimension_index_values: list[list[int]] | None = None + modality = { + LegacyConvertedEnhancedPETImageStorage: "pet", + LegacyConvertedEnhancedCTImageStorage: "ct", + LegacyConvertedEnhancedMRImageStorage: "mr", + }[self._destination.SOPClassUID] + + if harmonization_configs is None: + harmonization_configs = [] + + allowed_func_groups = _get_allowed_functional_groups( + modality, + include_enhanced_groups=include_enhanced_groups + ) + for h_cfg in harmonization_configs: + if h_cfg.destination_sequence_keyword not in allowed_func_groups: + raise ValueError( + "Harmonization configuration uses an inappropriate " + f"functional group: {h_cfg.destination_sequence_keyword}.." + ) + self._harmonization_configs = harmonization_configs + (self._keyword_shared_dict, self._private_tag_shared_dict) = ( self._find_shared_and_perframe_attributes() ) @@ -483,7 +564,7 @@ def __init__( "ImagesInAcquisition", ] self._unused_keywords = { - kw for kw in self._keyword_shared_dict.keys() + kw for kw in self._keyword_shared_dict if kw not in excluded_keywords } @@ -816,6 +897,181 @@ def __init__( required=False, ) + if include_enhanced_groups: + if ( + self._destination.SOPClassUID == + LegacyConvertedEnhancedCTImageStorage + ): + self._add_functional_group( + "CTAcquisitionDetailsSequence", + [], + optional_attributes=[ + _AttributeConfig("DataCollectionDiameter"), + _AttributeConfig("GantryDetectorTilt"), + _AttributeConfig("TableHeight"), + _AttributeConfig("RotationDirection"), + _AttributeConfig("RevolutionTime"), + _AttributeConfig("SingleCollimationWidth"), + _AttributeConfig("TotalCollimationWidth"), + ], + required=False, + ) + self._add_functional_group( + "CTReconstructionSequence", + [], + optional_attributes=[ + _AttributeConfig("ReconstructionDiameter"), + _AttributeConfig("ConvolutionKernel"), + ], + required=False, + ) + self._add_functional_group( + "CTPositionSequence", + [], + optional_attributes=[ + _AttributeConfig("DataCollectionCenterPatient"), + _AttributeConfig("ReconstructionTargetCenterPatient"), + ], + required=False, + ) + self._add_functional_group( + "CTXRayDetailsSequence", + [], + optional_attributes=[ + _AttributeConfig("KVP"), + _AttributeConfig("FilterType"), + _AttributeConfig("FocalSpots"), + _AttributeConfig("FilterMaterial"), + _AttributeConfig("CalciumScoringMassFactorPatient"), + _AttributeConfig("CalciumScoringMassFactorDevice"), + _AttributeConfig("EnergyWeightingFactor"), + ], + required=False, + ) + self._add_functional_group( + "CTExposureSequence", + [], + optional_attributes=[ + _AttributeConfig( + "ExposureTimeInms", + src_kws=["ExposureTimeInms", "ExposureTime"] + ), + _AttributeConfig( + "XRayTubeCurrentInmA", + src_kws=["XRayTubeCurrent", "XRayTubeCurrentInmA"], + ), + _AttributeConfig("ExposureInmAs"), + _AttributeConfig("ImageAndFluoroscopyAreaDoseProduct"), + _AttributeConfig("WaterEquivalentDiameter"), + _AttributeConfig( + "WaterEquivalentDiameterCalculationMethodCodeSequence" # noqa: E501 + ), + _AttributeConfig("ExposureModulationType"), + _AttributeConfig("CTDIvol"), + _AttributeConfig("CTDIPhantomTypeCodeSequence"), + ], + custom_logic_callback=( + self._ct_exposure_custom_logic + ), + required=False, + ) + self._add_functional_group( + "CTGeometrySequence", + [], + optional_attributes=[ + _AttributeConfig("DistanceSourceToDetector") + ], + required=False, + ) + self._add_functional_group( + "CTTableDynamicsSequence", + [], + optional_attributes=[ + _AttributeConfig("TableSpeed"), + _AttributeConfig("TableFeedPerRotation"), + _AttributeConfig("SpiralPitchFactor"), + ], + required=False, + ) + + self._copy_existing_sequence_to_functional_groups( + "CTAdditionalXRaySourceSequence" + ) + self._copy_existing_sequence_to_functional_groups( + "MultienergyCTCharacteristicsSequence" + ) + self._copy_existing_sequence_to_functional_groups( + "MultienergyCTProcessingSequence" + ) + + if ( + self._destination.SOPClassUID == + LegacyConvertedEnhancedMRImageStorage + ): + self._add_functional_group( + "MRFOVGeometrySequence", + [], + optional_attributes=[ + _AttributeConfig("PercentSampling"), + _AttributeConfig("PercentPhaseFieldOfView"), + _AttributeConfig("InPlanePhaseEncodingDirection"), + ], + required=False, + ) + self._add_functional_group( + "MRAveragesSequence", + [], + optional_attributes=[_AttributeConfig("NumberOfAverages")], + required=False, + ) + self._add_functional_group( + "MRTransmitCoilSequence", + [], + optional_attributes=[_AttributeConfig("TransmitCoilName")], + required=False, + ) + self._add_functional_group( + "MRTimingAndRelatedParametersSequence", + [], + optional_attributes=[ + _AttributeConfig("RepetitionTime"), + _AttributeConfig("EchoTrainLength"), + _AttributeConfig("FlipAngle"), + ], + required=False, + ) + self._add_functional_group( + "MRImagingModifierSequence", + [], + optional_attributes=[_AttributeConfig("PixelBandwidth")], + required=False, + ) + self._add_functional_group( + "MRReceiveCoilSequence", + [], + optional_attributes=[_AttributeConfig("ReceiveCoilName")], + required=False, + ) + + if ( + self._destination.SOPClassUID == + LegacyConvertedEnhancedPETImageStorage + ): + self._add_functional_group( + "PETReconstructionSequence", + [], + optional_attributes=[ + _AttributeConfig("ReconstructionDiameter") + ], + required=False, + ) + self._add_functional_group( + "PETFrameAcquisitionSequence", + [], + optional_attributes=[_AttributeConfig("TableHeight")], + required=False, + ) + # Functional grops where entire existing sequences are copied from the # source image self._copy_existing_sequence_to_functional_groups( @@ -836,7 +1092,10 @@ def __init__( def _find_shared_and_perframe_attributes( self, - ) -> tuple[dict[str, bool], dict[BaseTag, bool]]: + ) -> tuple[ + dict[str, bool], + dict[tuple[str, BaseTag], tuple[BaseTag, bool]] + ]: """Find attributes present in any dataset and whether they are shared. Returns @@ -846,55 +1105,60 @@ def _find_shared_and_perframe_attributes( any dataset. The corresponding value is a boolean that indicates whether that tag is consistent (in presence and value) across all datasets. - private_tag_shared_dict: dict[pydicom.tag.BaseTag, bool] - Dictionary whose keys include all (standard) keywords present in - any dataset. The corresponding value is a boolean that indicates - whether that tag is consistent (in presence and value) across all - datasets. + private_tag_shared_dict: dict[tuple[str, pydicom.BaseTag], tuple[pydicom.BaseTag, bool]] + Dictionary whose keys are "normalized" private tag present in any + dataset. The normalized tag consists of a tuple containing the + private creator str and a bitmasked version of the tag that removes + the bits indicating the specific location the tag was placed in + this dataset. This combination should be consistent across datasets + even if conflicting sets of private tags led to some tags being + moved to higher tags. + + The corresponding value is a tuple containing the original + (unnormalized) tag and boolean that indicates whether that tag is + consistent (in presence, value and location) across all datasets. - """ - all_keywords_present = set() - all_private_tags_present = set() + """ # noqa: E501 + standard_values_by_keyword: dict[str, list[Any]] = defaultdict(list) + private_values_by_creator_tag: dict[ + tuple[str, BaseTag, BaseTag], list[Any] + ] = defaultdict(list) for ds in self._legacy_datasets: - for t in ds.keys(): + for e in ds: if ( - not _istag_file_meta_information_group(t) and not - _istag_repeating_group(t) and not - _istag_group_length(t) + not _istag_file_meta_information_group(e.tag) and not + _istag_repeating_group(e.tag) and not + _istag_group_length(e.tag) and + e.tag != 0x7FE0_0010 # PixelData ): - if t.is_private and not self._skip_private_attributes: - if not t.is_private_creator: - all_private_tags_present.add(t) + if e.tag.is_private and not self._skip_private_attributes: + if not e.tag.is_private_creator: + private_values_by_creator_tag[ + (*_normalize_private_tag(e.tag, ds), e.tag) + ].append(e.value) else: - all_keywords_present.add(keyword_for_tag(t)) - - keyword_shared_dict: dict[str, bool] = {} - - for kw in all_keywords_present: - present_in_all = all(kw in ds for ds in self._legacy_datasets) + kw = keyword_for_tag(e.tag) + standard_values_by_keyword[kw].append(e.value) - same_value_in_all = False - if present_in_all: - ref_val = getattr(self._legacy_datasets[0], kw) - same_value_in_all = all( - getattr(ds, kw) == ref_val for ds in self._legacy_datasets - ) - - keyword_shared_dict[kw] = present_in_all and same_value_in_all - - private_tag_shared_dict: dict[BaseTag, bool] = {} - - for t in all_private_tags_present: - present_in_all = all(t in ds for ds in self._legacy_datasets) + keyword_shared_dict = { + kw: ( + len(values) == len(self._legacy_datasets) and + all(v == values[0] for v in values) + ) + for kw, values in standard_values_by_keyword.items() + } - same_value_in_all = False - if present_in_all: - ref_val = self._legacy_datasets[0][t].value - same_value_in_all = all( - ds[t].value == ref_val for ds in self._legacy_datasets + private_tag_shared_dict = { + (c, n): ( + t, + ( + len(vals) >= 1 and + len(vals) == len(self._legacy_datasets) and + all(v == vals[0] for v in vals) ) - - private_tag_shared_dict[t] = present_in_all and same_value_in_all + ) + for (c, n, t), vals in private_values_by_creator_tag.items() + } return keyword_shared_dict, private_tag_shared_dict @@ -1287,7 +1551,7 @@ def iter_attribute_configs( ) # First determine whether the module should be included - if module_usage != ModuleUsageValues.MANDATORY: + if module_usage != ModuleUsageValues.MANDATORY and self._strict: for dest_kw, _, _, _, val, _ in iter_attribute_configs(True): if val is None: # We have no value for one of the required attributes, so @@ -1378,6 +1642,7 @@ def _copy_to_functional_group( destination: Dataset, sequence_name: str, attribute_configs: list[_AttributeConfig], + harmonization_configs: list[HarmonizationConfig] | None = None, custom_logic_callback: Callable[[Dataset, Dataset], None] | None = None, ) -> None: """ @@ -1391,6 +1656,8 @@ def _copy_to_functional_group( Name of the sequence where the functional group will be placed. attribute_configs: list[highdicom.legacy.sop._AttributeConfig] Configurations for each attribute to place into the sequence. + harmonization_configs: list[highdicom.legacy.config.HarmonizationConfig] | None, optional + Harmonization configs with attributes in this functional group. custom_logic_callback: Callable[[pydicom.Dataset, pydicom.Dataset], None] | None Callback implementing custom logic to call after the other parameters have been copied. Takes the source and destination datasets as input @@ -1418,6 +1685,27 @@ def _copy_to_functional_group( if a_cfg.default_val is not None: setattr(item, a_cfg.dest_kw, a_cfg.default_val) + for h_cfg in (harmonization_configs or []): + params = [] + for t in h_cfg.source_tags: + if t.is_private: + tup = (cast(str, h_cfg.private_creator_name), t) + location_tag = self._private_tag_shared_dict[tup][0] + else: + location_tag = t + + if location_tag in source: + params.append(source[location_tag].value) + + if len(params) == len(h_cfg.source_tags): + if h_cfg.mapping is None: + out = params[0] + else: + out = h_cfg.mapping(*params) + + if out is not None: + setattr(item, h_cfg.destination_keyword, out) + if custom_logic_callback is not None: custom_logic_callback(source, item) @@ -1468,7 +1756,7 @@ def _add_functional_group( # If any attribute is per-frame, the whole functional group is # per-frame any_attr_is_per_frame = False - any_attr_exists = False + any_attr_has_source = False all_required_attrs_exist = True for configs, required_attr in zip( [required_attributes, optional_attributes], [True, False] @@ -1476,13 +1764,13 @@ def _add_functional_group( for a_cfg in configs: for kw in a_cfg.get_source_keywords(): if kw in self._keyword_shared_dict: - any_attr_exists = True + any_attr_has_source = True if not self._keyword_shared_dict[kw]: any_attr_is_per_frame = True break else: if a_cfg.default_val is not None: - any_attr_exists = True + any_attr_has_source = True elif required_attr: all_required_attrs_exist = False if required: @@ -1503,7 +1791,35 @@ def _add_functional_group( ) logger.warning(msg) - if not required and not all_required_attrs_exist: + harmonization_configs = [] + for h_cfg in self._harmonization_configs: + if h_cfg.destination_sequence_keyword != sequence_name: + continue + + all_harmonization_sources_exist = True + any_harmonization_source_is_per_frame = False + for t in h_cfg.source_tags: + if t.is_private: + tup = (cast(str, h_cfg.private_creator_name), t) + if tup in self._private_tag_shared_dict: + if not self._private_tag_shared_dict[tup][1]: + any_harmonization_source_is_per_frame = True + else: + all_harmonization_sources_exist = False + else: + kw = keyword_for_tag(t) + if kw in self._keyword_shared_dict: + if not self._keyword_shared_dict[kw]: + any_harmonization_source_is_per_frame = True + else: + all_harmonization_sources_exist = False + + if all_harmonization_sources_exist: + any_attr_has_source = True + any_attr_is_per_frame |= any_harmonization_source_is_per_frame + harmonization_configs.append(h_cfg) + + if self._strict and not required and not all_required_attrs_exist: # Do not include this functional group. Nothing more to do return @@ -1522,8 +1838,9 @@ def _add_functional_group( sequence_name=sequence_name, attribute_configs=attribute_configs, custom_logic_callback=custom_logic_callback, + harmonization_configs=harmonization_configs, ) - elif any_attr_exists or required: + elif any_attr_has_source or required: # Use the shared functional groups self._copy_to_functional_group( source=self._legacy_datasets[0], @@ -1531,6 +1848,7 @@ def _add_functional_group( sequence_name=sequence_name, attribute_configs=attribute_configs, custom_logic_callback=custom_logic_callback, + harmonization_configs=harmonization_configs, ) # Else nothing to copy @@ -1822,7 +2140,7 @@ def _frame_anatomy_custom_logic( "'FrameLaterality' will be left empty in the " "new legacy converted enhanced dataset." ) - logging.warning(msg) + logger.warning(msg) destination.FrameLaterality = src_laterality @@ -1873,6 +2191,30 @@ def _frame_content_custom_logic( destination.FrameAcquisitionDateTime = fa_dt + def _ct_exposure_custom_logic( + self, + source: Dataset, + destination: Dataset, + ) -> None: + """Custom logic for the CTExposureSequence. + + This is needed to handle unit conversion for exposure. + + Parameters + ---------- + source: pydicom.Dataset + Dataset to copy from. + destination: pydicom.Dataset + Dataset to copy to. + + """ + if ( + "ExposureInmAs" not in destination and + "ExposureInuAs" in source + ): + destination.ExposureInmAs = source.ExposureInuAs / 1000.0 + self._mark_keyword_used("ExposureInuAs") + def _add_series_description(self) -> None: """Add a default series description.""" suffix = " (enhanced conversion)" @@ -1995,7 +2337,7 @@ def _add_unassigned_attributes(self) -> None: if any( not self._keyword_shared_dict[kw] for kw in self._unused_keywords ) or any( - not shared for shared in self._private_tag_shared_dict.values() + not shared for (_, shared) in self._private_tag_shared_dict.values() ): for pffg in self._destination.PerFrameFunctionalGroupsSequence: pffg.UnassignedPerFrameConvertedAttributesSequence = [Dataset()] @@ -2024,7 +2366,7 @@ def _add_unassigned_attributes(self) -> None: ) # Private tags (these will all be unused at this stage) - for t, shared in self._private_tag_shared_dict.items(): + for (t, shared) in self._private_tag_shared_dict.values(): if shared: self._copy_private_attribute( t, @@ -2522,10 +2864,10 @@ class _CommonLegacyConvertedEnhancedImage(Image): """SOP class for common Legacy Converted Enhanced instances.""" # Override these on the sub-classes - _MODALITY_ATTRIBUTE = "" - _MODALITY_NAME = "" - _LEGACY_SOP_CLASS_UID = "" - _ENHANCED_SOP_CLASS_UID = "" + _MODALITY_ATTRIBUTE: str + _MODALITY_NAME: str + _LEGACY_SOP_CLASS_UID: str + _ENHANCED_SOP_CLASS_UID: str def __init__( self, @@ -2536,13 +2878,15 @@ def __init__( instance_number: int, *, transfer_syntax_uid: str | None = None, - use_extended_offset_table: bool = False, require_volume: bool = False, strict: bool = False, skip_private_attributes: bool = False, + include_dimension_index: bool | None = None, + include_enhanced_groups: bool = True, + harmonization_configs: list[HarmonizationConfig] | None = None, contributing_equipment: Sequence[ContributingEquipment] | None = None, + use_extended_offset_table: bool = False, workers: int | Executor = 0, - include_dimension_index: bool | None = None, **kwargs: Any, ) -> None: """ @@ -2572,15 +2916,23 @@ def __init__( are JPEG 2000 (``"1.2.840.10008.1.2.4.91"``) , JPEG 2000 Lossless (``"1.2.840.10008.1.2.4.90"``), and JPEG-LS Lossless (``"1.2.840.10008.1.2.4.80"``). - use_extended_offset_table: bool, optional - Include an extended offset table instead of a basic offset table - for encapsulated transfer syntaxes. Extended offset tables avoid - size limitations on basic offset tables, and separate the offset - table from the pixel data by placing it into metadata. However, - they may be less widely supported than basic offset tables. This - parameter is ignored if using a native (uncompressed) transfer - syntax. The default value may change in a future release. - include_dimension_index: bool | None = None, optional + require_volume: bool, optional + If True, raise an error if the legacy datasets do not represent a + set of parallel, regularly-spaced frames from the same series. This + is not a requirement for the conversion to be valid according to + the standard, but users may wish to additionally impose this + stricter requirement to ensure the resulting files are easier to + work with. + strict: bool, optional + Whether to use strict requirements on the new converted dataset. If + True and any attributes required to create a standard-compliant + Legacy Converted Enhanced instance are missing or inconsistent in + the legacy source files, an error will be raised. If False, a + warning will be raised in the same situation and the attribute will + be skipped in the new Legacy Converted Enhanced file. + skip_private_attributes: bool, optional + Whether to skip copying private attributes to the converted file. + include_dimension_index: bool | None, optional Whether to include a dimension index within the DimensionIndexSequence in the new converted dataset. A dimension index describes how the frames are ordered within the instance. @@ -2607,25 +2959,28 @@ def __init__( passed with no index. If ``False``, no attempt will be made to sort the datasets, they will be encoded in the order they are passed without including a dimension index. - require_volume: bool, optional - If True, raise an error if the legacy datasets do not represent a - set of parallel, regularly-spaced frames from the same series. This - is not a requirement for the conversion to be valid according to - the standard, but users may wish to additionally impose this - stricter requirement to ensure the resulting files are easier to - work with. - strict: bool, optional - Whether to use strict requirements on the new converted dataset. If - True and any attributes required to create a standard-compliant - Legacy Converted Enhanced instance are missing or inconsistent in - the legacy source files, an error will be raised. If False, a - warning will be raised in the same situation and the attribute will - be skipped in the new Legacy Converted Enhanced file. - skip_private_attributes: bool, optional - Whether to skip copying private attributes to the converted file. + include_enhanced_groups: bool, optional + Include multi-frame functional groups that are not part of the + Legacy Enhanced IOD, but are part of the corresponding Enhanced + IOD, if information exists in the legacy files to include in them. + If ``False``, only those groups explicitly included in the Legacy + Converted IOD are created in the new file, and any attributes that + do not belong in them are placed into the + UnassignedSharedConvertedAttributesSequence or + UnassignedPerFrameConvertedAttributesSequence. + harmonization_configs: list[highdicom.legacy.config.HarmonizationConfig] | None, optional + Harmonization configs with attributes in this functional group. contributing_equipment: Sequence[highdicom.ContributingEquipment] | None, optional Additional equipment that has contributed to the acquisition, creation or modification of this instance. + use_extended_offset_table: bool, optional + Include an extended offset table instead of a basic offset table + for encapsulated transfer syntaxes. Extended offset tables avoid + size limitations on basic offset tables, and separate the offset + table from the pixel data by placing it into metadata. However, + they may be less widely supported than basic offset tables. This + parameter is ignored if using a native (uncompressed) transfer + syntax. The default value may change in a future release. workers: int | concurrent.futures.Executor, optional Number of worker processes to use for frame compression, if compression or transcoding is needed. If 0, no workers are used and @@ -2698,36 +3053,12 @@ def __init__( ], instance_number=instance_number, transfer_syntax_uid=transfer_syntax_uid, - # Manufacturer is type 2 - manufacturer=getattr(ref_ds, "Manufacturer", None), - # Modality is type 1 modality=ref_ds.Modality, - # PatientID is type 2 - patient_id=getattr(ref_ds, "PatientID", None), - # PatientName is type 2 - patient_name=getattr(ref_ds, "PatientName", None), - # PatientBirthDate is type 2 - patient_birth_date=getattr(ref_ds, "PatientBirthDate", None), - # PatientSex is type 2 - patient_sex=getattr(ref_ds, "PatientSex", None), - # AccessionNumber is type 2 - accession_number=getattr(ref_ds, "AccessionNumber", None), - # StudyID is type 2 - study_id=getattr(ref_ds, "StudyID", None), - # StudyDate is type 2 - study_date=getattr(ref_ds, "StudyDate", None), - # StudyTime is type 2 - study_time=getattr(ref_ds, "StudyTime", None), - # ReferringPhysicianName is type 2 - referring_physician_name=getattr( - ref_ds, - "ReferringPhysicianName", - None - ), content_date=content_date, content_time=content_time, **kwargs, ) + # self.copy_patient_and_study_information(ref_ds) self._add_contributing_equipment( contributing_equipment, legacy_datasets[0], @@ -2739,13 +3070,15 @@ def __init__( _LegacyConversionRunner( legacy_datasets, destination=self, - workers=workers, + require_volume=require_volume, transfer_syntax_uid=transfer_syntax_uid, - use_extended_offset_table=use_extended_offset_table, include_dimension_index=include_dimension_index, - skip_private_attributes=skip_private_attributes, + include_enhanced_groups=include_enhanced_groups, + harmonization_configs=harmonization_configs, strict=strict, - require_volume=require_volume, + skip_private_attributes=skip_private_attributes, + use_extended_offset_table=use_extended_offset_table, + workers=workers, ) self._build_luts() diff --git a/src/highdicom/pixels.py b/src/highdicom/pixels.py index 5d1ce1e38..d0b7e5e77 100644 --- a/src/highdicom/pixels.py +++ b/src/highdicom/pixels.py @@ -40,12 +40,14 @@ def _parse_palette_color_lut_attributes(dataset: Dataset) -> tuple[ """ is_segmented = 'SegmentedRedPaletteColorLookupTableData' in dataset - if not is_segmented: - if 'RedPaletteColorLookupTableData' not in dataset: - raise AttributeError( - 'Dataset does not contain palette color lookup table ' - 'attributes.' - ) + if ( + not is_segmented and + 'RedPaletteColorLookupTableData' not in dataset + ): + raise AttributeError( + 'Dataset does not contain palette color lookup table ' + 'attributes.' + ) descriptor = dataset.RedPaletteColorLookupTableDescriptor if len(descriptor) != 3: @@ -107,7 +109,7 @@ def _parse_palette_color_lut_attributes(dataset: Dataset) -> tuple[ ) lut_bytes = getattr(dataset, data_kw) - if len(lut_bytes) != expected_num_bytes: + if not is_segmented and len(lut_bytes) != expected_num_bytes: raise RuntimeError( "LUT data has incorrect length" ) @@ -505,6 +507,132 @@ def apply_voi_window( return array +def _expand_segmented_lut( + segmented_lut_data: np.ndarray +) -> np.ndarray: + """Expand segmented LUT data to "standard" LUT representation. + + Parameters + ---------- + segmented_lut_data: numpy.ndarray + Segmented LUT data (consisting of opcodes and parameters) as a 1D numpy + array with dtype uint8 or uint16. + + Returns + ------- + numpy.ndarray: + Expanded representation of the segmented lut data. 1D numpy array with + the same dtype as the input array. + + """ + expanded_lut_values = [] + i = 0 + while i < len(segmented_lut_data): + opcode = segmented_lut_data[i] + if opcode == 0: + # Discrete segment type (literal) + length = segmented_lut_data[i + 1] + expanded_lut_values.extend( + segmented_lut_data[i + 2:i + 2 + length].tolist() + ) + i += (length + 2) + elif opcode == 1: + # Linear segment type (interpolation) + + # This type of segment may not be placed first as it requires the + # previous value + if i == 0: + raise ValueError( + "Error reading segmented LUT data, a linear segment may " + "not be used as the first segment." + ) + + length = segmented_lut_data[i + 1] + + # Need signed integers for subsequent calculations + start_value = int(expanded_lut_values[-1]) + end_value = int(segmented_lut_data[i + 2]) + step = (end_value - start_value) / length + + expanded_lut_values.extend([ + start_value + int(np.round(j * step)) + for j in range(1, length + 1) + ]) + i += 3 + elif opcode == 2: + # TODO + raise ValueError( + 'Indirect segment type is not yet supported for ' + 'Segmented Palette Color Lookup Table.' + ) + else: + raise ValueError( + f'Encountered unexpected segment type {opcode} for ' + 'Segmented Palette Color Lookup Table.' + ) + + return np.array(expanded_lut_values, dtype=segmented_lut_data.dtype) + + +def _get_expanded_lut_length( + segmented_lut_data: np.ndarray +) -> int: + """Get length of expanded segmented LUT data. + + This function does not expand the array to calculate the total length, and + is thus much more memory efficient than _expand_segmented_lut if only the + length is needed. + + Parameters + ---------- + segmented_lut_data: numpy.ndarray + Segmented LUT data (consisting of opcodes and parameters) as a 1D numpy + array with dtype uint8 or uint16. + + Returns + ------- + int: + Length (number of entries) of the expanded data. + + """ + total_length = 0 + i = 0 + while i < len(segmented_lut_data): + opcode = segmented_lut_data[i] + if opcode == 0: + # Discrete segment type (literal) + length = segmented_lut_data[i + 1] + total_length += length + i += (length + 2) + elif opcode == 1: + # Linear segment type (interpolation) + + # This type of segment may not be placed first as it requires the + # previous value + if i == 0: + raise ValueError( + "Error reading segmented LUT data, a linear segment may " + "not be used as the first segment." + ) + + length = segmented_lut_data[i + 1] + total_length += length + i += 3 + elif opcode == 2: + # TODO + raise ValueError( + 'Indirect segment type is not yet supported for ' + 'Segmented Palette Color Lookup Table.' + ) + else: + raise ValueError( + f'Encountered unexpected segment type {opcode} for ' + 'Segmented Palette Color Lookup Table.' + ) + + return int(total_length) + + def apply_lut( array: np.ndarray, lut_data: np.ndarray, diff --git a/src/highdicom/pm/sop.py b/src/highdicom/pm/sop.py index ff18ec8c6..c6c97cfb7 100644 --- a/src/highdicom/pm/sop.py +++ b/src/highdicom/pm/sop.py @@ -455,17 +455,6 @@ def __init__( sop_class_uid='1.2.840.10008.5.1.4.1.1.30', modality='OT', transfer_syntax_uid=transfer_syntax_uid, - patient_id=src_img.PatientID, - patient_name=src_img.PatientName, - patient_birth_date=src_img.PatientBirthDate, - patient_sex=src_img.PatientSex, - accession_number=src_img.AccessionNumber, - study_id=src_img.StudyID, - study_date=src_img.StudyDate, - study_time=src_img.StudyTime, - referring_physician_name=getattr( - src_img, 'ReferringPhysicianName', None - ), manufacturer=manufacturer, manufacturer_model_name=manufacturer_model_name, device_serial_number=device_serial_number, diff --git a/src/highdicom/pr/sop.py b/src/highdicom/pr/sop.py index e0b5a9fdb..def34918e 100644 --- a/src/highdicom/pr/sop.py +++ b/src/highdicom/pr/sop.py @@ -197,18 +197,7 @@ def __init__( sop_class_uid=GrayscaleSoftcopyPresentationStateStorage, instance_number=instance_number, modality='PR', - patient_id=ref_im.PatientID, transfer_syntax_uid=transfer_syntax_uid, - patient_name=ref_im.PatientName, - patient_birth_date=ref_im.PatientBirthDate, - patient_sex=ref_im.PatientSex, - accession_number=ref_im.AccessionNumber, - study_id=ref_im.StudyID, - study_date=ref_im.StudyDate, - study_time=ref_im.StudyTime, - referring_physician_name=getattr( - ref_im, 'ReferringPhysicianName', None - ), manufacturer=manufacturer, manufacturer_model_name=manufacturer_model_name, software_versions=software_versions, @@ -482,18 +471,7 @@ def __init__( sop_class_uid=PseudoColorSoftcopyPresentationStateStorage, instance_number=instance_number, modality='PR', - patient_id=ref_im.PatientID, transfer_syntax_uid=transfer_syntax_uid, - patient_name=ref_im.PatientName, - patient_birth_date=ref_im.PatientBirthDate, - patient_sex=ref_im.PatientSex, - accession_number=ref_im.AccessionNumber, - study_id=ref_im.StudyID, - study_date=ref_im.StudyDate, - study_time=ref_im.StudyTime, - referring_physician_name=getattr( - ref_im, 'ReferringPhysicianName', None - ), manufacturer=manufacturer, manufacturer_model_name=manufacturer_model_name, software_versions=software_versions, @@ -766,18 +744,7 @@ def __init__( sop_class_uid=ColorSoftcopyPresentationStateStorage, instance_number=instance_number, modality='PR', - patient_id=ref_im.PatientID, transfer_syntax_uid=transfer_syntax_uid, - patient_name=ref_im.PatientName, - patient_birth_date=ref_im.PatientBirthDate, - patient_sex=ref_im.PatientSex, - accession_number=ref_im.AccessionNumber, - study_id=ref_im.StudyID, - study_date=ref_im.StudyDate, - study_time=ref_im.StudyTime, - referring_physician_name=getattr( - ref_im, 'ReferringPhysicianName', None - ), manufacturer=manufacturer, manufacturer_model_name=manufacturer_model_name, software_versions=software_versions, @@ -978,18 +945,7 @@ def __init__( sop_class_uid=AdvancedBlendingPresentationStateStorage, instance_number=instance_number, modality='PR', - patient_id=ref_im.PatientID, transfer_syntax_uid=transfer_syntax_uid, - patient_name=ref_im.PatientName, - patient_birth_date=ref_im.PatientBirthDate, - patient_sex=ref_im.PatientSex, - accession_number=ref_im.AccessionNumber, - study_id=ref_im.StudyID, - study_date=ref_im.StudyDate, - study_time=ref_im.StudyTime, - referring_physician_name=getattr( - ref_im, 'ReferringPhysicianName', None - ), manufacturer=manufacturer, manufacturer_model_name=manufacturer_model_name, software_versions=software_versions, diff --git a/src/highdicom/sc/sop.py b/src/highdicom/sc/sop.py index c7d3b7015..536a5e98e 100644 --- a/src/highdicom/sc/sop.py +++ b/src/highdicom/sc/sop.py @@ -5,6 +5,7 @@ from typing import Any from collections.abc import Sequence from typing_extensions import Self +import warnings import numpy as np from pydicom.uid import SecondaryCaptureImageStorage @@ -24,6 +25,10 @@ JPEGLSNearLossless, ) +from highdicom._standard_utils import ( + does_iod_have_pixel_data, + is_multiframe_image, +) from highdicom.base import SOPClass from highdicom.base_content import ContributingEquipment from highdicom.content import ( @@ -39,80 +44,101 @@ PatientOrientationValuesQuadruped, PatientSexValues, ) +from highdicom.image import Image from highdicom.frame import encode_frame from highdicom.sc.enum import ConversionTypeValues +from highdicom.spatial import ( + _check_image_orientation, + _get_spatial_information, + create_rotation_matrix, + get_closest_patient_orientation, + get_image_coordinate_system, +) from highdicom.sr.coding import CodedConcept -from highdicom.valuerep import check_person_name +from highdicom.valuerep import ( + check_person_name, + _check_long_string, +) logger = logging.getLogger(__name__) -class SCImage(SOPClass): +class SCImage(Image): """SOP class for a Secondary Capture (SC) Image, which represents a single-frame image that was converted from a non-DICOM format. """ def __init__( - self, - pixel_array: np.ndarray, - photometric_interpretation: ( - str | - PhotometricInterpretationValues - ), - bits_allocated: int, - coordinate_system: str | CoordinateSystemNames, - study_instance_uid: str, - series_instance_uid: str, - series_number: int, - sop_instance_uid: str, - instance_number: int, - manufacturer: str, - patient_id: str | None = None, - patient_name: str | PersonName | None = None, - patient_birth_date: str | None = None, - patient_sex: str | PatientSexValues | None = None, - accession_number: str | None = None, - study_id: str | None = None, - study_date: str | datetime.date | None = None, - study_time: str | datetime.time | None = None, - referring_physician_name: str | PersonName | None = None, - pixel_spacing: tuple[float, float] | None = None, - laterality: str | LateralityValues | None = None, - patient_orientation: ( - tuple[str, str] | - tuple[ - PatientOrientationValuesBiped, - PatientOrientationValuesBiped, - ] | - tuple[ - PatientOrientationValuesQuadruped, - PatientOrientationValuesQuadruped, - ] - ) | None = None, - anatomical_orientation_type: None | ( - str | AnatomicalOrientationTypeValues - ) = None, - container_identifier: str | None = None, - issuer_of_container_identifier: IssuerOfIdentifier | None = None, - specimen_descriptions: None | ( - Sequence[SpecimenDescription] - ) = None, - transfer_syntax_uid: str = ExplicitVRLittleEndian, - contributing_equipment: Sequence[ - ContributingEquipment - ] | None = None, - **kwargs: Any - ): + self, + pixel_array: np.ndarray, + photometric_interpretation: ( + str | + PhotometricInterpretationValues + ), + coordinate_system: str | CoordinateSystemNames, + study_instance_uid: str, + series_instance_uid: str, + series_number: int, + sop_instance_uid: str, + instance_number: int, + manufacturer: str, + patient_id: str | None = None, + patient_name: str | PersonName | None = None, + patient_birth_date: str | None = None, + patient_sex: str | PatientSexValues | None = None, + accession_number: str | None = None, + study_id: str | None = None, + study_date: str | datetime.date | None = None, + study_time: str | datetime.time | None = None, + referring_physician_name: str | PersonName | None = None, + pixel_spacing: tuple[float, float] | None = None, + laterality: str | LateralityValues | None = None, + patient_orientation: ( + tuple[str, str] | + tuple[ + PatientOrientationValuesBiped, + PatientOrientationValuesBiped, + ] | + tuple[ + PatientOrientationValuesQuadruped, + PatientOrientationValuesQuadruped, + ] + ) | None = None, + anatomical_orientation_type: None | ( + str | AnatomicalOrientationTypeValues + ) = None, + container_identifier: str | None = None, + issuer_of_container_identifier: IssuerOfIdentifier | None = None, + specimen_descriptions: None | ( + Sequence[SpecimenDescription] + ) = None, + transfer_syntax_uid: str = ExplicitVRLittleEndian, + contributing_equipment: Sequence[ + ContributingEquipment + ] | None = None, + *, + bits_stored: int | None = None, + bits_allocated: int | None = None, + image_position: Sequence[float] | None = None, + image_orientation: Sequence[float] | None = None, + slice_thickness: float | None = None, + spacing_between_slices: float | None = None, + frame_of_reference_uid: str | None = None, + position_reference_indicator: str | None = None, + **kwargs: Any, + ): """ Parameters ---------- pixel_array: numpy.ndarray - Array of unsigned integer pixel values representing a single-frame - image; either a 2D grayscale image or a 3D color image - (RGB color space) + Array of pixel values representing a single-frame image; either a + 2D grayscale image with shape (H, W) or a 3D color image with shape + (H, W, 3) in the RGB color space. Acceptable datatypes are bool, + uint8, uint16, int8, or int16 for grayscale images, and uint8 or + uint16 for color images. photometric_interpretation: Union[str, highdicom.PhotometricInterpretationValues] Interpretation with which to store pixel data in the dataset; either ``"MONOCHROME1"`` or ``"MONOCHROME2"`` for single channel @@ -125,8 +151,6 @@ def __init__( ``photometric_interpretation must be ``"YBR_ICT"``, if ``transfer_syntax_uid`` is ``"JPEG2000Lossless"``, ``photometric_interpretation must be ``"YBR_RCT"``. - bits_allocated: int - Number of bits that should be allocated per pixel value coordinate_system: Union[str, highdicom.CoordinateSystemNames] Subject (``"PATIENT"`` or ``"SLIDE"``) that was the target of imaging @@ -167,10 +191,12 @@ def __init__( column dimension laterality: Union[str, highdicom.LateralityValues, None], optional Laterality of the examined body part - patient_orientation: - Union[Tuple[str, str], Tuple[highdicom.PatientOrientationValuesBiped, highdicom.PatientOrientationValuesBiped], Tuple[highdicom.PatientOrientationValuesQuadruped, highdicom.PatientOrientationValuesQuadruped], None], optional + patient_orientation: Union[Tuple[str, str], Tuple[highdicom.PatientOrientationValuesBiped, highdicom.PatientOrientationValuesBiped], Tuple[highdicom.PatientOrientationValuesQuadruped, highdicom.PatientOrientationValuesQuadruped], None], optional Orientation of the patient along the row and column axes of the - image (required if `coordinate_system` is ``"PATIENT"``) + image. Required if `coordinate_system` is ``"PATIENT"`` and + ``image_orientation`` is not provided. If ``image_orientation`` is + provided, it will be used to infer the correct value for + ``patient_orientation``. anatomical_orientation_type: Union[str, highdicom.AnatomicalOrientationTypeValues, None], optional Type of anatomical orientation of patient relative to image (may be provide if `coordinate_system` is ``"PATIENT"`` and patient is @@ -195,6 +221,41 @@ def __init__( contributing_equipment: Sequence[highdicom.ContributingEquipment] | None, optional Additional equipment that has contributed to the acquisition, creation or modification of this instance. + bits_stored: int | None, optional + Number of bits that should be stored per pixel value. By default, + the number of bits per pixel in the input array is assumed. Any + provided value must be less than or equal to the number of bits per + pixel in the input array. + bits_allocated: int | None, optional + *Deprecated* in highdicom 0.29.0. This was previously the name for + the ``bits_stored`` parameter, but this name was deprecated because + it incorrectly described how the attribute was used in the + resulting DICOM image. For backwards compatibility, passing + ``bits_allocated`` is equivalent to passing ``bits_stored`` and + controls the bits stored in the file. This parameter will be + removed entirely in a future release. To upgrade, pass the value + to the keyword-only ``bits_stored`` parameter instead. + image_position: Sequence[float] | None, optional + Position, in mm, of the center of the top left pixel in the + frame-of reference-coordinate system. Must contain exactly 3 + values. Pass only if using the "PATIENT" coordinate system. + image_orientation: Sequence[float] | None, optional + Direction cosines of the image within the frame-of-reference + coordinate system. Must contain exactly 6 values. Pass only if + using the "PATIENT" coordinate system. + slice_thickness: float | None, optional + Slice thickness of the image in mm. Pass only if using the + "PATIENT" coordinate system. + spacing_between_slices: float | None, optional + Spacing between slices, in mm. Pass only if using the "PATIENT" + coordinate system. + frame_of_reference_uid: str | None = None, optional + Frame of reference UID, required if 'image_orientation' and + 'image_orientation' are provided. + position_reference_indicator: str | None = None, optional + Description of the part of the imaging target used to define the + frame-of-reference coordinate system. Should only be provided + if 'frame_of_reference_uid' is provided. **kwargs: Any, optional Additional keyword arguments that will be passed to the constructor of `highdicom.base.SOPClass` @@ -221,7 +282,8 @@ def __init__( if referring_physician_name is not None: check_person_name(referring_physician_name) - super().__init__( + SOPClass.__init__( + self, study_instance_uid=study_instance_uid, series_instance_uid=series_instance_uid, series_number=series_number, @@ -244,14 +306,20 @@ def __init__( ) self._add_contributing_equipment(contributing_equipment) + # If we received an integer for coordinate_system, assume that the user + # is using the old signature that included the deprecated + # 'bits_allocated' with positional arguments + if isinstance(bits_allocated, int): + raise TypeError( + "Use of 'bits_allocated' as a positional argument was " + "deprecated in highdicom 0.29.0. Omit the parameter to use " + "the number of bits per pixel in the input array as both " + "the number of bits allocated and bits stored or specify " + "'bits_stored' as a keyword argument." + ) + coordinate_system = CoordinateSystemNames(coordinate_system) if coordinate_system == CoordinateSystemNames.PATIENT: - if patient_orientation is None: - raise TypeError( - 'Patient orientation is required if coordinate system ' - 'is "PATIENT".' - ) - # General Series if laterality is not None: laterality = LateralityValues(laterality) @@ -268,20 +336,6 @@ def __init__( anatomical_orientation_type = \ AnatomicalOrientationTypeValues.BIPED - row_orientation, col_orientation = patient_orientation - if (anatomical_orientation_type == - AnatomicalOrientationTypeValues.BIPED): - patient_orientation = ( - PatientOrientationValuesBiped(row_orientation).value, - PatientOrientationValuesBiped(col_orientation).value, - ) - else: - patient_orientation = ( - PatientOrientationValuesQuadruped(row_orientation).value, - PatientOrientationValuesQuadruped(col_orientation).value, - ) - self.PatientOrientation = list(patient_orientation) - elif coordinate_system == CoordinateSystemNames.SLIDE: if container_identifier is None: raise TypeError( @@ -318,34 +372,16 @@ def __init__( self.ImageType = ['DERIVED', 'SECONDARY', 'OTHER'] self.Rows = pixel_array.shape[0] self.Columns = pixel_array.shape[1] - allowed_types = [np.bool_, np.uint8, np.uint16] - if not any(pixel_array.dtype == t for t in allowed_types): - raise TypeError( - 'Pixel array must be of type np.bool_, np.uint8 or np.uint16. ' - f'Found {pixel_array.dtype}.' - ) - wrong_bit_depth_assignment = ( - pixel_array.dtype == np.bool_ and bits_allocated != 1, - pixel_array.dtype == np.uint8 and bits_allocated != 8, - pixel_array.dtype == np.uint16 and bits_allocated not in (12, 16), - ) - if any(wrong_bit_depth_assignment): - raise ValueError('Pixel array has an unexpected bit depth.') - if bits_allocated not in (1, 8, 12, 16): - raise ValueError('Unexpected number of bits allocated.') - if transfer_syntax_uid == RLELossless and bits_allocated % 8 != 0: - raise ValueError( - 'When using run length encoding, bits allocated must be a ' - 'multiple of 8' - ) - self.BitsAllocated = bits_allocated - self.HighBit = self.BitsAllocated - 1 - self.BitsStored = self.BitsAllocated - self.PixelRepresentation = 0 + photometric_interpretation = PhotometricInterpretationValues( photometric_interpretation ) if pixel_array.ndim == 3: + if pixel_array.shape[-1] != 3: + raise ValueError( + 'Pixel array has an unexpected number of color channels.' + ) + if transfer_syntax_uid == JPEGBaseline8Bit: accepted_interpretations = { PhotometricInterpretationValues.YBR_FULL_422.value, @@ -363,40 +399,171 @@ def __init__( PhotometricInterpretationValues.RGB.value, PhotometricInterpretationValues.YBR_FULL.value, } + if photometric_interpretation.value not in accepted_interpretations: raise ValueError( 'Pixel array has an unexpected photometric interpretation.' ) - if pixel_array.shape[-1] != 3: - raise ValueError( - 'Pixel array has an unexpected number of color channels.' + + if pixel_array.dtype.kind != 'u': + raise TypeError( + 'Pixel array must have an unsigned ' + 'integer datatype for color images. ' + f'Found {pixel_array.dtype}.' ) - if bits_allocated != 8: - raise ValueError('Color images must be 8-bit.') - if pixel_array.dtype != np.uint8: + + self.BitsAllocated = pixel_array.itemsize * 8 + + if self.BitsAllocated not in (1, 8, 16, 32): raise TypeError( - 'Pixel array must have 8-bit unsigned integer data type ' - 'in case of a color image.' + 'Pixel array has an unexpected bit depth.' ) + self.PhotometricInterpretation = photometric_interpretation.value self.SamplesPerPixel = 3 self.PlanarConfiguration = 0 + self.PixelRepresentation = 0 + elif pixel_array.ndim == 2: accepted_interpretations = { PhotometricInterpretationValues.MONOCHROME1.value, PhotometricInterpretationValues.MONOCHROME2.value, } + if photometric_interpretation.value not in accepted_interpretations: raise ValueError( 'Pixel array has an unexpected photometric interpretation.' ) + + if pixel_array.dtype.kind == 'b': + self.BitsAllocated = 1 + self.PixelRepresentation = 0 + elif pixel_array.dtype.kind == 'u': + self.PixelRepresentation = 0 + self.BitsAllocated = pixel_array.itemsize * 8 + elif pixel_array.dtype.kind == 'i': + self.PixelRepresentation = 1 + self.BitsAllocated = pixel_array.itemsize * 8 + else: + raise TypeError( + 'Pixel array must have signed or unsigned ' + 'integer datatype for monochrome images. ' + f'Found {pixel_array.dtype}.' + ) + + if self.BitsAllocated not in (1, 8, 16, 32): + raise TypeError( + 'Pixel array has an unexpected bit depth.' + ) + self.PhotometricInterpretation = photometric_interpretation.value self.SamplesPerPixel = 1 else: raise ValueError( 'Pixel array has an unexpected number of dimensions.' ) + + if bits_allocated is not None: + # Handle deprecation of bits_allocated + if bits_stored is not None: + raise TypeError( + "The 'bits_allocated' parameter is deprecated and must " + "not be provided alongside 'bits_stored'." + ) + + warnings.warn( + "The 'bits_allocated' parameter is deprecated as of highdicom " + "0.29.0 and will be removed in a future version of the " + "library. Use 'bits_stored' to set the number of bits stored " + "or skip the parameter entirely to use the number of bits per " + "pixel in the input array as the number of bits allocated.", + UserWarning, + stacklevel=2, + ) + # Interpret the bits_allocated as bits_stored in line with the old, + # deprecated behavior + bits_stored = bits_allocated + + if bits_stored is not None: + if not isinstance(bits_stored, int): + raise TypeError("Parameter 'bits_stored' must be an integer.") + + if bits_stored < 1 or bits_stored > self.BitsAllocated: + raise ValueError( + "'bits_stored' must be an integer no greater than the " + "number of bits per pixel in the input array." + ) + + self.BitsStored = bits_stored + + if ( + bits_stored != self.BitsAllocated and + pixel_array.max() >= 2 ** bits_stored + ): + raise ValueError( + "Provided 'pixel_array' cannot be represented with the " + f"specified number of 'bits_stored' ({bits_stored})." + ) + else: + # By default, assume the full range of pixel values in the input + # array + self.BitsStored = self.BitsAllocated + + self.HighBit = self.BitsStored - 1 + + if patient_orientation is not None: + if len(patient_orientation) != 2: + raise ValueError( + "Wrong number of items in 'patient_orientation'." + ) + row_orientation, col_orientation = patient_orientation + if ( + anatomical_orientation_type == + AnatomicalOrientationTypeValues.BIPED + ): + patient_orientation = ( + PatientOrientationValuesBiped(row_orientation), + PatientOrientationValuesBiped(col_orientation), + ) + else: + patient_orientation = ( + PatientOrientationValuesQuadruped(row_orientation), + PatientOrientationValuesQuadruped(col_orientation), + ) + + if frame_of_reference_uid is not None: + self.FrameOfReferenceUID = frame_of_reference_uid + if position_reference_indicator is not None: + if ( + coordinate_system == CoordinateSystemNames.SLIDE and + position_reference_indicator != "SLIDE_CORNER" + ): + raise ValueError( + "'position_reference_indicator' must be " + "'SLIDE_CORNER' when using the slide" + "coordinate system. Leave this argument " + "unspecified to use this default." + ) + + _check_long_string(position_reference_indicator) + + elif coordinate_system == CoordinateSystemNames.SLIDE: + # This is the only valid value for slides + position_reference_indicator = "SLIDE_CORNER" + + # Type 2, set to empty if parameter is None and using PATIENT + # coordinate system + self.PositionReferenceIndicator = position_reference_indicator + elif position_reference_indicator is not None: + raise TypeError( + "Argument 'position_reference_indicator' may not be provided " + "if 'frame_of_reference_uid' is not provided." + ) + if pixel_spacing is not None: + # Note that pixel spacing apepars in both the Image Plane module + # (as type 1) and the SC Image module (as type !C). So it can be + # included regardless of whether position/orientation are included if len(pixel_spacing) != 2: raise ValueError( 'Argument "pixel_spacing" should have length 2.' @@ -405,6 +572,124 @@ def __init__( DS(ps, auto_format=True) for ps in pixel_spacing ] + # The Image Plane moduie is User defined "U" in the SC Image IOD + if (image_position is None) != (image_orientation is None): + # Both position and orientation are required if the Image Plane + # moduleu is to be included + raise TypeError( + "Both 'image_position' and 'image_orientation' must be " + "provided if either is provided." + ) + + if image_position is not None and image_orientation is not None: + + if coordinate_system != CoordinateSystemNames.PATIENT: + raise TypeError( + "Arguments 'image_orientation' and 'image_position' are " + "only valid when using the 'PATIENT' coordinate system." + ) + + # In this case, PixelSpacing is type 1. Setting the attribute + # occurred above, ir present + if pixel_spacing is None: + raise TypeError( + "Argument 'pixel_spacing' is required if 'image_position' " + "and 'image_orientation' are provided." + ) + + # Frame of Reference Module is required if ImagePosition is present + if frame_of_reference_uid is None: + raise TypeError( + "Argument 'frame_of_reference_uid' is required if " + "'image_position' and 'image_orientation' are provided." + ) + + if len(image_position) != 3: + raise ValueError( + "Argument 'image_position' must have length 3." + ) + + self.ImagePositionPatient = [ + DS(p, auto_format=True) for p in image_position + ] + _check_image_orientation(image_orientation) + self.ImageOrientationPatient = [ + DS(p, auto_format=True) for p in image_orientation + ] + + if slice_thickness is not None: + self.SliceThickness = DS(slice_thickness, auto_format=True) + else: + # Type 2 in Image Plane module + self.SliceThickness = None + + if spacing_between_slices is not None: + # Type 3 - skip if not provided + self.SpacingBetweenSlices = DS( + spacing_between_slices, + auto_format=True + ) + + if ( + anatomical_orientation_type == + AnatomicalOrientationTypeValues.BIPED + ): + # For the BIPED case, we can check the patient orientation + # given the image orientation. For quadrupeds, this is trickier + # because it depends where you are in the body + calculated_patient_orientation = ( + get_closest_patient_orientation( + create_rotation_matrix(image_orientation) + )[:-1] + ) + + if ( + patient_orientation is not None and + patient_orientation != calculated_patient_orientation + ): + raise ValueError( + "The provided 'patient_orientation' is not consistent " + "with the provided value for 'image_orientation'. " + "Leave 'patient_orientation' unspecified to infer its " + "value from 'image_orientation'." + ) + + patient_orientation = calculated_patient_orientation + + else: + if coordinate_system == CoordinateSystemNames.PATIENT: + # We are using the patient coordinate system, but not including + # the Image Plane module. Therefore the optional Image Plane + # attributes should not be provided + reason = ( + "in combination with 'image_position' and " + "'image_orientation'." + ) + + if patient_orientation is None: + raise TypeError( + "Patient orientation is required if coordinate system " + "is 'PATIENT' amd 'image_orientation' is not provided." + ) + else: + # Trying to include Image Plane module in a coordinate system + # other than patient is not allowed + reason = "when using the 'PATIENT' coordinate system." + + if slice_thickness is not None: + raise TypeError( + f"Argugment 'slice_thickness' may only be provided {reason}" + ) + + if spacing_between_slices is not None: + raise TypeError( + f"Argugment 'spacing_between_slices' may only be provided " + f"{reason}" + ) + + if patient_orientation is not None: + self.PatientOrientation = [p.value for p in patient_orientation] + encoded_frame = encode_frame( pixel_array, transfer_syntax_uid=self.file_meta.TransferSyntaxUID, @@ -412,13 +697,16 @@ def __init__( bits_stored=self.BitsStored, photometric_interpretation=self.PhotometricInterpretation, pixel_representation=self.PixelRepresentation, - planar_configuration=getattr(self, 'PlanarConfiguration', None) + planar_configuration=self.get('PlanarConfiguration'), ) if self.file_meta.TransferSyntaxUID.is_encapsulated: self.PixelData = encapsulate([encoded_frame]) else: self.PixelData = encoded_frame + self._build_luts() + self._file_reader = None + @classmethod def from_ref_dataset( cls, @@ -428,14 +716,13 @@ def from_ref_dataset( str | PhotometricInterpretationValues ), - bits_allocated: int, coordinate_system: str | CoordinateSystemNames, series_instance_uid: str, series_number: int, sop_instance_uid: str, instance_number: int, manufacturer: str, - pixel_spacing: tuple[int, int] | None = None, + pixel_spacing: tuple[float, float] | None = None, laterality: str | LateralityValues | None = None, patient_orientation: ( tuple[str, str] | @@ -460,19 +747,27 @@ def from_ref_dataset( contributing_equipment: Sequence[ ContributingEquipment ] | None = None, + *, + bits_stored: int | None = None, + bits_allocated: int | None = None, + image_position: Sequence[float] | None = None, + image_orientation: Sequence[float] | None = None, + slice_thickness: float | None = None, + spacing_between_slices: float | None = None, + frame_of_reference_uid: str | None = None, + position_reference_indicator: str | None = None, **kwargs: Any ) -> Self: - """Constructor that copies patient and study from an existing dataset. + """Constructor that copies patient/study data from an existing dataset. This provides a more concise way to construct an SCImage when an existing reference dataset from the study is available. All patient- and study- related attributes required by the main constructor are copied from the ``ref_dataset``, if present. - The ``ref_dataset`` may be any dataset - from the study to which the resulting SC image should belong, and - contain all the relevant patient and study metadata. It does not need to - be specifically related to the contents of the SCImage. + The ``ref_dataset`` may be any dataset from the study to which the + resulting SC image should belong, and contain all the relevant patient + and study metadata. Parameters ---------- @@ -533,6 +828,37 @@ def from_ref_dataset( contributing_equipment: Sequence[highdicom.ContributingEquipment] | None, optional Additional equipment that has contributed to the acquisition, creation or modification of this instance. + bits_stored: int | None, optional + Number of bits that should be stored per pixel value. By default, + the number of bits per pixel in the input array is assumed. Any + provided value must be less than or equal to the number of bits per + pixel in the input array. + bits_allocated: int | None, optional + *Deprecated* in highdicom 0.29.0. This was previously the name for + the ``bits_stored`` parameter, but this name was deprecated because + it incorrectly described how the attribute was used in the + resulting DICOM image. For backwards compatibility, passing + ``bits_allocated`` is equivalent to passing ``bits_stored`` and + controls the bits stored in the file. This parameter will be + removed entirely in a future release. + image_position: Sequence[float] | None, optional + Position, in mm, of the center of the top left pixel in the + frame-of reference-coordinate system. Must contain exactly 3 + values. + image_orientation: Sequence[float] | None, optional + Direction cosines of the image within the frame-of-reference + coordinate system. Must contain exactly 6 values. + slice_thickness: float | None, optional + Slice thickness of the image in mm. + spacing_between_slices: float | None, optional + Spacing between slices, in mm. + frame_of_reference_uid: str | None = None, optional + Frame of reference UID, required if 'image_orientation' and + 'image_orientation' are provided. + position_reference_indicator: str | None = None, optional + Description of the part of the imaging target used to define the + frame-of-reference coordinate system. Should only be provided + if 'frame_of_reference_uid' is provided. **kwargs: Any, optional Additional keyword arguments that will be passed to the constructor of `highdicom.base.SOPClass` @@ -562,12 +888,13 @@ def from_ref_dataset( if 'specific_character_set' in kwargs: specific_character_set = kwargs.pop('specific_character_set') else: - specific_character_set = ref_dataset.get('SpecificCharacterSet') + specific_character_set = ref_dataset.get( + 'SpecificCharacterSet' + ) - return cls( + sc = cls( pixel_array=pixel_array, photometric_interpretation=photometric_interpretation, - bits_allocated=bits_allocated, coordinate_system=coordinate_system, study_instance_uid=ref_dataset.StudyInstanceUID, series_instance_uid=series_instance_uid, @@ -575,19 +902,6 @@ def from_ref_dataset( sop_instance_uid=sop_instance_uid, instance_number=instance_number, manufacturer=manufacturer, - patient_id=getattr(ref_dataset, 'PatientID', None), - patient_name=getattr(ref_dataset, 'PatientName', None), - patient_birth_date=getattr(ref_dataset, 'PatientBirthDate', None), - patient_sex=getattr(ref_dataset, 'PatientSex', None), - accession_number=getattr(ref_dataset, 'AccessionNumber', None), - study_id=getattr(ref_dataset, 'StudyID', None), - study_date=getattr(ref_dataset, 'StudyDate', None), - study_time=getattr(ref_dataset, 'StudyTime', None), - referring_physician_name=getattr( - ref_dataset, - 'ReferringPhysicianName', - None - ), pixel_spacing=pixel_spacing, laterality=laterality, patient_orientation=patient_orientation, @@ -598,5 +912,184 @@ def from_ref_dataset( transfer_syntax_uid=transfer_syntax_uid, contributing_equipment=contributing_equipment, specific_character_set=specific_character_set, + bits_stored=bits_stored, + bits_allocated=bits_allocated, + image_position=image_position, + image_orientation=image_orientation, + slice_thickness=slice_thickness, + spacing_between_slices=spacing_between_slices, + frame_of_reference_uid=frame_of_reference_uid, + position_reference_indicator=position_reference_indicator, **kwargs ) + sc.copy_patient_and_study_information(ref_dataset) + sc.copy_specimen_information(ref_dataset) + + return sc + + @classmethod + def from_aligned_ref_image( + cls, + ref_image: Dataset, + pixel_array: np.ndarray, + *, + photometric_interpretation: ( + str | + PhotometricInterpretationValues + ), + series_instance_uid: str, + series_number: int, + sop_instance_uid: str, + instance_number: int, + manufacturer: str, + transfer_syntax_uid: str = ImplicitVRLittleEndian, + contributing_equipment: Sequence[ + ContributingEquipment + ] | None = None, + bits_stored: int | None = None, + **kwargs: Any + ) -> Self: + """Constructor that copies patient/study and spatial data from an + existing dataset. + + This is similar to :class:`highdicom.sc.SCImage.from_ref_dataset`, but + additionally copies spatial information from the reference dataset. + This is only possible when the reference dataset represents an image in + the "PATIENT" coordinate system, and only correct if the new secondary + capture image is spatially aligned pixel-for-pixel with the reference + image. + + Parameters + ---------- + ref_image: pydicom.dataset.Dataset + An existing image, spatially aligned with the new SC image and + belonging to the study to which the SCImage should belong. Patient- + and study-related and spatial metadata will be copied from this + image. + pixel_array: numpy.ndarray + Array of unsigned integer pixel values representing a single-frame + image; either a 2D grayscale image or a 3D color image + (RGB color space) + photometric_interpretation: Union[str, highdicom.PhotometricInterpretationValues] + Interpretation of pixel data; either ``"MONOCHROME1"`` or + ``"MONOCHROME2"`` for 2D grayscale images or ``"RGB"`` or + ``"YBR_FULL"`` for 3D color images + bits_allocated: int + Number of bits that should be allocated per pixel value + series_instance_uid: str + Series Instance UID of the SC image series + series_number: int + Series Number of the SC image series + sop_instance_uid: str + SOP instance UID that should be assigned to the SC image instance + instance_number: int + Number that should be assigned to this SC image instance + manufacturer: str + Name of the manufacturer of the device that creates the SC image + instance (in a research setting this is typically the same + as `institution_name`) + transfer_syntax_uid: str, optional + UID of transfer syntax that should be used for encoding of + data elements. The following lossless compressed transfer syntaxes + are supported: RLE Lossless (``"1.2.840.10008.1.2.5"``), JPEG 2000 + Lossless (``"1.2.840.10008.1.2.4.90"``). + contributing_equipment: Sequence[highdicom.ContributingEquipment] | None, optional + Additional equipment that has contributed to the acquisition, + creation or modification of this instance. + bits_stored: int | None, optional + Number of bits that should be stored per pixel value. By default, + the number of bits per pixel in the input array is assumed. Any + provided value must be less than or equal to the number of bits per + pixel in the input array. + **kwargs: Any, optional + Additional keyword arguments that will be passed to the constructor + of `highdicom.base.SOPClass` + + Returns + ------- + SCImage + Secondary capture image. + + """ # noqa: E501 + # Attempt to copy spatial information from the reference dataset + # This is only valid in the patient coordinate system and if the + # image sizes match + coordinate_system = get_image_coordinate_system(ref_image) + if coordinate_system != CoordinateSystemNames.PATIENT: + raise ValueError( + "Using 'from_aligned_ref_image' is only possible " + "when using the 'PATIENT' coordinate system." + ) + + if not does_iod_have_pixel_data(ref_image.SOPClassUID): + raise ValueError( + "'ref_image' must be an image when using " + "'from_aligned_ref_image'." + ) + + if is_multiframe_image(ref_image): + raise ValueError( + "'ref_image' must be a single frame image when using " + "'from_aligned_ref_image'." + ) + if pixel_array.shape[:2] != (ref_image.Rows, ref_image.Columns): + raise ValueError( + "Shape of 'pixel_array' must match rows and columns of " + "'ref_image' when using 'from_aligned_ref_image'." + ) + + ( + image_position, + image_orientation, + pixel_spacing, + spacing_between_slices, + ) = _get_spatial_information(ref_image) + + slice_thickness = ref_image.get('SliceThickness') + laterality = ref_image.get('Laterality') + frame_of_reference_uid = ref_image.FrameOfReferenceUID + position_reference_indicator = ref_image.get( + 'PositionReferenceIndicator' + ) + + if laterality not in ('L', 'R'): + # Do not fail due to invalid laterality values in the reference + laterality = None + + anatomical_orientation_type = ref_image.get('AnatomicalOrientationType') + + patient_orientation = None + if ( + anatomical_orientation_type is not None and + anatomical_orientation_type == + AnatomicalOrientationTypeValues.QUADRUPED.value + ): + # Otherwise it will be inferred from image orientation in the main + # constructor + patient_orientation = ref_image.get('PatientOrientation') + + return cls.from_ref_dataset( + ref_dataset=ref_image, + pixel_array=pixel_array, + photometric_interpretation=photometric_interpretation, + coordinate_system=coordinate_system, + series_instance_uid=series_instance_uid, + series_number=series_number, + sop_instance_uid=sop_instance_uid, + instance_number=instance_number, + manufacturer=manufacturer, + laterality=laterality, + anatomical_orientation_type=anatomical_orientation_type, + transfer_syntax_uid=transfer_syntax_uid, + contributing_equipment=contributing_equipment, + bits_stored=bits_stored, + image_position=image_position, + image_orientation=image_orientation, + pixel_spacing=pixel_spacing, + slice_thickness=slice_thickness, + spacing_between_slices=spacing_between_slices, + frame_of_reference_uid=frame_of_reference_uid, + position_reference_indicator=position_reference_indicator, + patient_orientation=patient_orientation, + **kwargs, + ) diff --git a/src/highdicom/seg/__init__.py b/src/highdicom/seg/__init__.py index 9b109e2cb..cb0d7e667 100644 --- a/src/highdicom/seg/__init__.py +++ b/src/highdicom/seg/__init__.py @@ -9,6 +9,7 @@ ) from highdicom.seg.content import ( SegmentDescription, + SegmentedPropertyType, DimensionIndexSequence, ) from highdicom.seg import utils @@ -26,6 +27,7 @@ 'Segmentation', 'SegmentationFractionalTypeValues', 'SegmentationTypeValues', + 'SegmentedPropertyType', 'SegmentsOverlapValues', 'SpatialLocationsPreservedValues', 'create_segmentation_pyramid', diff --git a/src/highdicom/seg/content.py b/src/highdicom/seg/content.py index 32486a3f6..57dd0a596 100644 --- a/src/highdicom/seg/content.py +++ b/src/highdicom/seg/content.py @@ -11,19 +11,37 @@ from highdicom.color import CIELabColor from highdicom.content import ( AlgorithmIdentificationSequence, + AnatomicRegion, + PrimaryAnatomicStructure, ) from highdicom.enum import ( CoordinateSystemNames, ) from highdicom.image import _DimensionIndexSequence from highdicom.seg.enum import SegmentAlgorithmTypeValues -from highdicom.sr.coding import CodedConcept +from highdicom.sr.coding import CodedConcept, _ModifiedCodedConcept from highdicom._standard_utils import ( check_required_attributes, ) from highdicom.volume import ChannelDescriptor +class SegmentedPropertyType(_ModifiedCodedConcept): + """Dataset describing the property a segmentation represents. + + This class may be used instead of a plain + :class:`highdicom.sr.CodedConcept` in order to include modifier codes that + describe characteristics of the segmented property, such as laterality. + + See :dcm:`CID 7151 ` "Segmentation Property + Types" for the appropriate context group for the root concept, and + :dcm:`CID 2 ` "Anatomic Modifier" for the context + group for modifier codes. + + """ + _MODIFIER_SEQUENCE_NAME = "SegmentedPropertyTypeModifierCodeSequence" + + class SegmentDescription(Dataset): """Dataset describing a segment based on the Segment Description macro. @@ -39,7 +57,7 @@ def __init__( segment_number: int, segment_label: str, segmented_property_category: Code | CodedConcept, - segmented_property_type: Code | CodedConcept, + segmented_property_type: Code | CodedConcept | SegmentedPropertyType, algorithm_type: SegmentAlgorithmTypeValues | str, algorithm_identification: None | ( AlgorithmIdentificationSequence @@ -47,10 +65,10 @@ def __init__( tracking_uid: str | None = None, tracking_id: str | None = None, anatomic_regions: None | ( - Sequence[Code | CodedConcept] + Sequence[Code | CodedConcept | AnatomicRegion] ) = None, primary_anatomic_structures: None | ( - Sequence[Code | CodedConcept] + Sequence[Code | CodedConcept | PrimaryAnatomicStructure] ) = None, display_color: CIELabColor | None = None, ) -> None: @@ -61,16 +79,18 @@ def __init__( Number of the segment. segment_label: str Label of the segment - segmented_property_category: Union[pydicom.sr.coding.Code, highdicom.sr.CodedConcept] + segmented_property_category: Union[pydicom.sr.coding.Code, highdicom.sr.CodedConcept, highdicom.seg.SegmentedPropertyType] Category of the property the segment represents, e.g. ``Code("49755003", "SCT", "Morphologically Abnormal Structure")`` (see :dcm:`CID 7150 ` "Segmentation Property Categories") - segmented_property_type: Union[pydicom.sr.coding.Code, highdicom.sr.CodedConcept] + segmented_property_type: Union[pydicom.sr.coding.Code, highdicom.sr.CodedConcept, highdicom.seg.SegmentedPropertyType] Property the segment represents, e.g. ``Code("108369006", "SCT", "Neoplasm")`` - (see :dcm:`CID 7151 ` - "Segmentation Property Types") + (see :dcm:`CID 7151 ` "Segmentation + Property Types"). Use a + :class:`highdicom.seg.SegmentedPropertyType` to pass a code with + modifiers (such as specifying laterality). algorithm_type: Union[str, highdicom.seg.SegmentAlgorithmTypeValues] Type of algorithm algorithm_identification: Union[highdicom.AlgorithmIdentificationSequence, None], optional @@ -84,16 +104,20 @@ def __init__( Tracking identifier (unique only with the domain of use). This is intended to provide an identifier to track this segment across multiple imaging studies. - anatomic_regions: Union[Sequence[Union[pydicom.sr.coding.Code, highdicom.sr.CodedConcept]], None], optional + anatomic_regions: Union[Sequence[Union[pydicom.sr.coding.Code, highdicom.sr.CodedConcept, highdicom.AnatomicRegion]], None], optional Anatomic region(s) into which segment falls, e.g. ``Code("41216001", "SCT", "Prostate")`` (see :dcm:`CID 4 ` "Anatomic Region", :dcm:`CID 4031 ` "Common Anatomic Regions", as as well as other CIDs for - domain-specific anatomic regions) - primary_anatomic_structures: Union[Sequence[Union[pydicom.sr.coding.Code, highdicom.sr.CodedConcept]], None], optional - Anatomic structure(s) the segment represents - (see CIDs for domain-specific primary anatomic structures) + domain-specific anatomic regions). Use a list of + :class:`highdicom.AnatomicRegion` to pass a code with + modifiers (such as specifying laterality). + primary_anatomic_structures: Union[Sequence[Union[pydicom.sr.coding.Code, highdicom.sr.CodedConcept, highdicom.PrimaryAnatomicStructure]], None], optional + Anatomic structure(s) the segment represents (see CIDs for + domain-specific primary anatomic structures). Use a list of + :class:`highdicom.PrimaryAnatomicStructure` to pass a code with + modifiers (such as specifying laterality). display_color: Union[highdicom.color.CIELabColor, None], optional A recommended color to render this segment. @@ -111,12 +135,35 @@ def __init__( ) self.SegmentNumber = segment_number self.SegmentLabel = segment_label + + if isinstance(segmented_property_category, _ModifiedCodedConcept): + raise TypeError( + "Argument 'segmented_property_category' should not have " + f"type {segmented_property_category.__class__.__name__}." + ) + self.SegmentedPropertyCategoryCodeSequence = [ CodedConcept.from_code(segmented_property_category) ] + + if ( + isinstance(segmented_property_type, _ModifiedCodedConcept) and not + isinstance(segmented_property_type, SegmentedPropertyType) + ): + raise TypeError( + "Argument 'segmented_property_type' should not have " + f"type {segmented_property_type.__class__.__name__}." + ) + + if not isinstance(segmented_property_type, SegmentedPropertyType): + segmented_property_type = SegmentedPropertyType( + segmented_property_type + ) + self.SegmentedPropertyTypeCodeSequence = [ - CodedConcept.from_code(segmented_property_type) + segmented_property_type ] + algorithm_type = SegmentAlgorithmTypeValues(algorithm_type) self.SegmentAlgorithmType = algorithm_type.value if algorithm_identification is None: @@ -133,10 +180,12 @@ def __init__( algorithm_identification[0].AlgorithmName self.SegmentationAlgorithmIdentificationSequence = \ algorithm_identification + num_given_tracking_identifiers = sum([ tracking_id is not None, tracking_uid is not None ]) + if num_given_tracking_identifiers == 2: self.TrackingID = tracking_id self.TrackingUID = tracking_uid @@ -144,16 +193,54 @@ def __init__( raise TypeError( 'Tracking ID and Tracking UID must both be provided.' ) - if anatomic_regions is not None: - self.AnatomicRegionSequence = [ - CodedConcept.from_code(region) - for region in anatomic_regions - ] - if primary_anatomic_structures is not None: - self.PrimaryAnatomicStructureSequence = [ - CodedConcept.from_code(structure) - for structure in primary_anatomic_structures - ] + + if anatomic_regions is not None and len(anatomic_regions) > 0: + checked_regions = [] + + for region in anatomic_regions: + if ( + isinstance(region, _ModifiedCodedConcept) and not + isinstance(region, AnatomicRegion) + ): + raise TypeError( + "Items of 'anatomic_regions' should not have " + f"type {region.__class__.__name__}." + ) + + if isinstance(region, AnatomicRegion): + checked_regions.append(region) + else: + checked_regions.append( + AnatomicRegion(region) + ) + + self.AnatomicRegionSequence = checked_regions + + if ( + primary_anatomic_structures is not None and + len(primary_anatomic_structures) > 0 + ): + checked_structures = [] + + for structure in primary_anatomic_structures: + if ( + isinstance(structure, _ModifiedCodedConcept) and not + isinstance(structure, PrimaryAnatomicStructure) + ): + raise TypeError( + "Items of 'primary_anatomic_structures' should not " + f"have type {structure.__class__.__name__}." + ) + + if isinstance(structure, PrimaryAnatomicStructure): + checked_structures.append(structure) + else: + checked_structures.append( + PrimaryAnatomicStructure(structure) + ) + + self.PrimaryAnatomicStructureSequence = checked_structures + if display_color is not None: if not isinstance(display_color, CIELabColor): raise TypeError( @@ -210,7 +297,7 @@ def from_dataset( ) ] desc.SegmentedPropertyTypeCodeSequence = [ - CodedConcept.from_dataset( + SegmentedPropertyType.from_dataset( desc.SegmentedPropertyTypeCodeSequence[0], copy=False, ) @@ -223,12 +310,12 @@ def from_dataset( ) if hasattr(desc, 'AnatomicRegionSequence'): desc.AnatomicRegionSequence = [ - CodedConcept.from_dataset(ds, copy=False) + AnatomicRegion.from_dataset(ds, copy=False) for ds in desc.AnatomicRegionSequence ] if hasattr(desc, 'PrimaryAnatomicStructureSequence'): desc.PrimaryAnatomicStructureSequence = [ - CodedConcept.from_dataset(ds, copy=False) + PrimaryAnatomicStructure.from_dataset(ds, copy=False) for ds in desc.PrimaryAnatomicStructureSequence ] return cast(Self, desc) @@ -252,8 +339,8 @@ def segmented_property_category(self) -> CodedConcept: return self.SegmentedPropertyCategoryCodeSequence[0] @property - def segmented_property_type(self) -> CodedConcept: - """highdicom.sr.CodedConcept: + def segmented_property_type(self) -> SegmentedPropertyType: + """highdicom.seg.SegmentedPropertyType: Type of the property the segment represents. """ @@ -297,8 +384,8 @@ def tracking_id(self) -> str | None: return None @property - def anatomic_regions(self) -> list[CodedConcept]: - """List[highdicom.sr.CodedConcept]: + def anatomic_regions(self) -> list[AnatomicRegion]: + """List[highdicom.AnatomicRegion]: List of anatomic regions into which the segment falls. May be empty. @@ -308,8 +395,8 @@ def anatomic_regions(self) -> list[CodedConcept]: return list(self.AnatomicRegionSequence) @property - def primary_anatomic_structures(self) -> list[CodedConcept]: - """List[highdicom.sr.CodedConcept]: + def primary_anatomic_structures(self) -> list[PrimaryAnatomicStructure]: + """List[highdicom.PrimaryAnatomicStructure]: List of anatomic anatomic structures the segment represents. May be empty. diff --git a/src/highdicom/seg/sop.py b/src/highdicom/seg/sop.py index 3108724d9..51524680e 100644 --- a/src/highdicom/seg/sop.py +++ b/src/highdicom/seg/sop.py @@ -46,7 +46,7 @@ PhotometricInterpretationValues, PixelRepresentationValues, ) -from highdicom.seg.content import SegmentDescription +from highdicom.seg.content import SegmentDescription, SegmentedPropertyType from highdicom.seg.enum import ( SegmentationFractionalTypeValues, SegmentationTypeValues, @@ -54,7 +54,7 @@ SegmentAlgorithmTypeValues, ) from highdicom.seg.utils import iter_segments -from highdicom.sr.coding import CodedConcept +from highdicom.sr.coding import CodedConcept, codes_equal from highdicom.volume import ( ChannelDescriptor, Volume, @@ -132,6 +132,24 @@ def _check_numpy_value_representation( ) +def _property_type_matches( + actual: SegmentedPropertyType, + query: Code | CodedConcept | SegmentedPropertyType, +) -> bool: + """Check whether a segment's property type matches a filter value. + + If the query is a :class:`highdicom.seg.SegmentedPropertyType`, the root + code and all modifiers must match. Otherwise, only the unmodified root code + is compared. + + """ + return codes_equal( + actual, + query, + ignore_modifiers=not isinstance(query, SegmentedPropertyType), + ) + + class Segmentation(_Image): """SOP class for the Segmentation IOD. @@ -519,17 +537,6 @@ def __init__( manufacturer=manufacturer, modality='SEG', transfer_syntax_uid=transfer_syntax_uid, - patient_id=src_img.PatientID, - patient_name=src_img.PatientName, - patient_birth_date=src_img.PatientBirthDate, - patient_sex=src_img.PatientSex, - accession_number=src_img.AccessionNumber, - study_id=src_img.StudyID, - study_date=src_img.StudyDate, - study_time=src_img.StudyTime, - referring_physician_name=getattr( - src_img, 'ReferringPhysicianName', None - ), manufacturer_model_name=manufacturer_model_name, device_serial_number=device_serial_number, software_versions=software_versions, @@ -1477,7 +1484,9 @@ def get_segment_numbers( self, segment_label: str | None = None, segmented_property_category: Code | CodedConcept | None = None, - segmented_property_type: Code | CodedConcept | None = None, + segmented_property_type: ( + Code | CodedConcept | SegmentedPropertyType | None + ) = None, algorithm_type: SegmentAlgorithmTypeValues | str | None = None, tracking_uid: str | None = None, tracking_id: str | None = None, @@ -1493,8 +1502,17 @@ def get_segment_numbers( Segment label filter to apply. segmented_property_category: Union[Code, CodedConcept, None], optional Segmented property category filter to apply. - segmented_property_type: Union[Code, CodedConcept, None], optional - Segmented property type filter to apply. + segmented_property_type: Union[Code, CodedConcept, highdicom.seg.SegmentedPropertyType, None], optional + Segmented property type filter to apply. If a + :class:`highdicom.seg.SegmentedPropertyType` is provided, a segment + matches only if its segmented property type has the same root code + *and* exactly the same set of modifier codes (in any order). A + ``SegmentedPropertyType`` without modifiers therefore matches only + segments whose type has no modifiers. If a plain + :class:`pydicom.sr.coding.Code` or + :class:`highdicom.sr.CodedConcept` is provided, only the root + (unmodified) code is compared, and any modifiers on the segment's + type are ignored. algorithm_type: Union[SegmentAlgorithmTypeValues, str, None], optional Segmented property type filter to apply. tracking_uid: Union[str, None], optional @@ -1526,6 +1544,28 @@ def get_segment_numbers( >>> segment_numbers [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] + Filter by segmented property type including modifiers. Passing a plain + code matches the root code only, ignoring any modifiers, whereas + passing a :class:`highdicom.seg.SegmentedPropertyType` requires the + modifiers to match exactly (though order does not matter). Here no + segments have a modifier, so only the unmodified type matches: + + >>> from highdicom.seg import SegmentedPropertyType + >>> seg.get_segment_numbers( + ... segmented_property_type=SegmentedPropertyType( + ... codes.SCT.ConnectiveTissue, + ... modifiers=[codes.SCT.Left], + ... ) + ... ) + [] + >>> segment_numbers = seg.get_segment_numbers( + ... segmented_property_type=SegmentedPropertyType( + ... codes.SCT.ConnectiveTissue + ... ) + ... ) + >>> len(segment_numbers) + 20 + Get segment numbers of all segments identified by a given institution-specific tracking ID: @@ -1556,8 +1596,10 @@ def get_segment_numbers( ) if segmented_property_type is not None: filter_funcs.append( - lambda desc: - desc.segmented_property_type == segmented_property_type + lambda desc: _property_type_matches( + desc.segmented_property_type, + segmented_property_type, + ) ) if algorithm_type is not None: algo_type = SegmentAlgorithmTypeValues(algorithm_type) @@ -1587,7 +1629,9 @@ def get_segment_numbers( def get_tracking_ids( self, segmented_property_category: Code | CodedConcept | None = None, - segmented_property_type: Code | CodedConcept | None = None, + segmented_property_type: ( + Code | CodedConcept | SegmentedPropertyType | None + ) = None, algorithm_type: SegmentAlgorithmTypeValues | str | None = None ) -> list[tuple[str, UID]]: """Get all unique tracking identifiers in this SEG image. @@ -1605,8 +1649,12 @@ def get_tracking_ids( ---------- segmented_property_category: Union[pydicom.sr.coding.Code, highdicom.sr.CodedConcept, None], optional Segmented property category filter to apply. - segmented_property_type: Union[pydicom.sr.coding.Code, highdicom.sr.CodedConcept, None], optional - Segmented property type filter to apply. + segmented_property_type: Union[pydicom.sr.coding.Code, highdicom.sr.CodedConcept, highdicom.seg.SegmentedPropertyType, None], optional + Segmented property type filter to apply. Matching follows the same + rules as in :meth:`get_segment_numbers`: a + :class:`highdicom.seg.SegmentedPropertyType` must match the root + code and all modifiers, whereas a plain code matches the root code + only. algorithm_type: Union[highdicom.seg.SegmentAlgorithmTypeValues, str, None], optional Segmented property type filter to apply. @@ -1653,8 +1701,10 @@ def get_tracking_ids( ) if segmented_property_type is not None: filter_funcs.append( - lambda desc: - desc.segmented_property_type == segmented_property_type + lambda desc: _property_type_matches( + desc.segmented_property_type, + segmented_property_type, + ) ) if algorithm_type is not None: algo_type = SegmentAlgorithmTypeValues(algorithm_type) @@ -1697,12 +1747,16 @@ def segmented_property_categories(self) -> list[CodedConcept]: return categories @property - def segmented_property_types(self) -> list[CodedConcept]: + def segmented_property_types(self) -> list[SegmentedPropertyType]: """Get all unique non-background segmented property types. + Types are considered unique based on both their root code and their + modifiers (in any order), so the same root code with different + modifiers is listed separately. + Returns ------- - List[CodedConcept] + List[highdicom.seg.SegmentedPropertyType] All unique non-background segmented property types referenced in segment descriptions in this SEG image. diff --git a/src/highdicom/spatial.py b/src/highdicom/spatial.py index 97d01d37e..7676e9c0c 100644 --- a/src/highdicom/spatial.py +++ b/src/highdicom/spatial.py @@ -1143,8 +1143,7 @@ def create_rotation_matrix( x, y, z position in the frame-of-reference coordinate system. """ # noqa: E501 - if len(image_orientation) != 6: - raise ValueError('Argument "image_orientation" must have length 6.') + _check_image_orientation(image_orientation) index_convention_ = _normalize_pixel_index_convention(index_convention) handedness_ = AxisHandedness(handedness) @@ -1236,6 +1235,49 @@ def _stack_affine_matrix( ) +def _check_image_orientation(image_orientation: Sequence[float]): + """Check that a sequence of flaots is a valid image orientation. + + To be valid, an image orientation must consist of six numbers between -1 + and 1 (inclusive) that form two orthogonal unit vector concatenated + end-to-end. + + Parameters + ---------- + image_orientation: Sequence[float] + User-passed image orientation. + + Raises + ------ + ValueError: + If the image orientation is not a valid set of direction cosines. + + """ + if not isinstance(image_orientation, (Sequence, np.ndarray)): + raise TypeError('Argument "image_orientation" must be a sequence.') + if len(image_orientation) != 6: + raise ValueError('Argument "image_orientation" must have length 6.') + + if max(image_orientation) > 1.0 or min(image_orientation) < -1.0: + raise ValueError( + "Values in image_orientation must be in the range -1 to 1." + ) + + row_cosines = np.array(image_orientation[:3], dtype=float) + column_cosines = np.array(image_orientation[3:], dtype=float) + + for a in [row_cosines, column_cosines]: + if np.abs(np.linalg.norm(a) - 1.0) > _DEFAULT_ORTHOGONAL_TOLERANCE: + raise ValueError( + "Image orientation must contain unit vectors." + ) + + if np.abs(row_cosines.T @ column_cosines) > _DEFAULT_ORTHOGONAL_TOLERANCE: + raise ValueError( + "Image orientation must contain two orthogonal vectors." + ) + + def create_affine_matrix_from_attributes( image_position: Sequence[float], image_orientation: Sequence[float], @@ -1314,14 +1356,11 @@ def create_affine_matrix_from_attributes( raise TypeError('Argument "image_position" must be a sequence.') if len(image_position) != 3: raise ValueError('Argument "image_position" must have length 3.') - if not isinstance(image_orientation, (Sequence, np.ndarray)): - raise TypeError('Argument "image_orientation" must be a sequence.') - if len(image_orientation) != 6: - raise ValueError('Argument "image_orientation" must have length 6.') if not isinstance(pixel_spacing, (Sequence, np.ndarray)): raise TypeError('Argument "pixel_spacing" must be a sequence.') if len(pixel_spacing) != 2: raise ValueError('Argument "pixel_spacing" must have length 2.') + # image_orientation is checked within create_rotation_matrix index_convention_ = _normalize_pixel_index_convention(index_convention) if ( @@ -1406,14 +1445,11 @@ def _create_inv_affine_matrix_from_attributes( raise TypeError('Argument "image_position" must be a sequence.') if len(image_position) != 3: raise ValueError('Argument "image_position" must have length 3.') - if not isinstance(image_orientation, Sequence): - raise TypeError('Argument "image_orientation" must be a sequence.') - if len(image_orientation) != 6: - raise ValueError('Argument "image_orientation" must have length 6.') if not isinstance(pixel_spacing, Sequence): raise TypeError('Argument "pixel_spacing" must be a sequence.') if len(pixel_spacing) != 2: raise ValueError('Argument "pixel_spacing" must have length 2.') + # image_orientation is checked within create_rotation_matrix translation = np.array([float(x) for x in image_position], dtype=float) diff --git a/src/highdicom/sr/__init__.py b/src/highdicom/sr/__init__.py index 4d1c31a9b..307957705 100644 --- a/src/highdicom/sr/__init__.py +++ b/src/highdicom/sr/__init__.py @@ -1,5 +1,5 @@ """Package for creation of Structured Report (SR) instances.""" -from highdicom.sr.coding import CodedConcept +from highdicom.sr.coding import CodedConcept, codes_equal from highdicom.sr.content import ( CoordinatesForMeasurement, CoordinatesForMeasurement3D, @@ -52,6 +52,7 @@ SubjectContextDevice, SubjectContextFetus, SubjectContextSpecimen, + TextEvaluation, TrackingIdentifier, TimePointContext, VolumetricROIMeasurementsAndQualitativeEvaluations, @@ -154,6 +155,7 @@ 'TcoordContentItem', 'TemporalRangeTypeValues', 'TextContentItem', + 'TextEvaluation', 'TimeContentItem', 'TimePointContext', 'TrackingIdentifier', @@ -162,6 +164,7 @@ 'VolumeSurface', 'VolumetricROIMeasurementsAndQualitativeEvaluations', 'WaveformContentItem', + 'codes_equal', 'srread', 'utils', ] diff --git a/src/highdicom/sr/coding.py b/src/highdicom/sr/coding.py index f7053bbf7..2d63d4510 100644 --- a/src/highdicom/sr/coding.py +++ b/src/highdicom/sr/coding.py @@ -1,3 +1,4 @@ +from collections.abc import Sequence from copy import deepcopy import logging from typing import Union @@ -55,6 +56,16 @@ def __hash__(self) -> int: def __eq__(self, other: object) -> bool: """Compares `self` and `other` for equality. + Two codes are equal if they represent the same concept, with the same + set of modifiers (if the codes support modifiers). See + :func:`highdicom.sr.codes_equal`. + + Note that this operator is not symmetric when `other` is a + ``pydicom.sr.coding.Code``: ``code == modified_concept`` is evaluated + by pydicom, which disregards any modifiers. Use + :func:`highdicom.sr.codes_equal` to compare codes in a way that is + safe regardless of argument order. + Parameters ---------- other: Union[highdicom.sr.CodedConcept, pydicom.sr.coding.Code] @@ -67,13 +78,7 @@ def __eq__(self, other: object) -> bool: """ if isinstance(other, (Code, CodedConcept)): - this = Code( - self.value, - self.scheme_designator, - self.meaning, - self.scheme_version - ) - return Code.__eq__(this, other) + return codes_equal(self, other) return super().__eq__(other) def __ne__(self, other: object) -> bool: @@ -196,3 +201,271 @@ def scheme_designator(self) -> str: def scheme_version(self) -> str | None: """Union[str, None]: version of the coding scheme (if specified)""" return getattr(self, 'CodingSchemeVersion', None) + + +class _ModifiedCodedConcept(CodedConcept): + + """Base class for Coded Concepts that have a modifier sequence. + + The name of the modifier sequence varies depending on context and is + controlled by a class variable. + + """ + _MODIFIER_SEQUENCE_NAME: str # overrider on subclasses + + def __init__( + self, + coded_concept: Code | CodedConcept, + modifiers: Sequence[Code | CodedConcept] | None = None, + ): + """ + + Parameters + ---------- + coded_concept: pydicom.sr.coding.Code | highdicom.sr.CodedConcept + The root coded concept. The class docstring gives the appropriate + context group. If this is an instance of the same class, its + modifiers are carried over (and any further `modifiers` are + appended to them). Instances of other modified classes are not + accepted, since their modifiers belong to a different context. + modifiers: Sequence[pydicom.sr.coding.Code | highdicom.sr.CodedConcept] | None + Modifier codes that optionally describe characteristics of the root + concept. The class docstring gives the appropriate context group. + + Raises + ------ + TypeError: + If `coded_concept` is an instance of a different modified coded + concept class, or if `coded_concept` or any item of `modifiers` + has an invalid type. + + """ # noqa: E501 + if not isinstance(coded_concept, (Code, CodedConcept)): + raise TypeError( + "Argument 'coded_concept' must be either " + "pydicom.sr.coding.Code or highdicom.sr.CodedConcept." + ) + + if ( + isinstance(coded_concept, _ModifiedCodedConcept) and not + isinstance(coded_concept, type(self)) + ): + raise TypeError( + "Argument 'coded_concept' must not be an instance of " + f"{type(coded_concept).__name__} since this would discard " + "its modifiers." + ) + + super().__init__( + value=coded_concept.value, + scheme_designator=coded_concept.scheme_designator, + meaning=coded_concept.meaning, + scheme_version=coded_concept.scheme_version, + ) + + checked_modifiers: list[CodedConcept] = [] + if isinstance(coded_concept, _ModifiedCodedConcept): + checked_modifiers.extend(coded_concept.modifiers) + + for modifier in (modifiers or []): + if isinstance(modifier, Code): + checked_modifiers.append(CodedConcept.from_code(modifier)) + elif isinstance(modifier, CodedConcept): + checked_modifiers.append(modifier) + else: + raise TypeError( + "Items of 'modifiers' must be either " + "pydicom.sr.coding.Code or highdicom.sr.CodedConcept." + ) + + if len(checked_modifiers) > 0: + setattr(self, self._MODIFIER_SEQUENCE_NAME, checked_modifiers) + + @classmethod + def from_code(cls, code: Union[Code, 'CodedConcept']) -> Self: + """Construct a _ModifiedCodedConcept for a pydicom Code. + + Parameters + ---------- + code: Union[pydicom.sr.coding.Code, highdicom.sr.CodedConcept] + Code. + + Returns + ------- + Self: + CodedConcept dataset for the code. + + """ + if isinstance(code, cls): + return code + return cls(code) + + @classmethod + def from_dataset( + cls, + dataset: Dataset, + copy: bool = True + ) -> Self: + """Construct a modified Coded Concept from an existing dataset. + + Parameters + ---------- + dataset: pydicom.dataset.Dataset + Dataset representing a coded concept. + copy: bool + If True, the underlying dataset is deep-copied such that the + original dataset remains intact. If False, this operation will + alter the original dataset in place. + + Returns + ------- + Self: + Coded concept representation of the dataset. + + Raises + ------ + TypeError: + If the passed dataset is not a pydicom dataset. + AttributeError: + If the dataset does not contain the required elements for a + coded concept. + + """ + concept = super().from_dataset(dataset, copy=copy) + + if hasattr(concept, cls._MODIFIER_SEQUENCE_NAME): + modifiers = [ + # no need for a further copy + CodedConcept.from_dataset(m, copy=False) + for m in getattr(concept, cls._MODIFIER_SEQUENCE_NAME) + ] + setattr(concept, cls._MODIFIER_SEQUENCE_NAME, modifiers) + + return concept + + @property + def unmodified(self) -> CodedConcept: + """highdicom.sr.CodedConcept: The coded concept with any modifiers + removed. + + """ + return CodedConcept( + value=self.value, + scheme_designator=self.scheme_designator, + meaning=self.meaning, + scheme_version=self.scheme_version, + ) + + @property + def modifiers(self) -> tuple[CodedConcept, ...]: + """tuple[highdicom.sr.CodedConcept, ...]: tuple of concept modifiers + """ + if not hasattr(self, self._MODIFIER_SEQUENCE_NAME): + return () + + # No copy is needed: this is an in-place (and idempotent) class change + # of items that already represent coded concepts + return tuple( + CodedConcept.from_dataset(ds, copy=False) for ds in + getattr(self, self._MODIFIER_SEQUENCE_NAME) + ) + + def __hash__(self) -> int: + root = self.scheme_designator + self.value + modifiers = self.modifiers + + if len(modifiers) == 0: + # Must match the hash of a plain CodedConcept or pydicom Code, which + # compare equal to an unmodified code + return hash(root) + + parts = [ + root, + *sorted([mod.scheme_designator + mod.value for mod in modifiers]) + ] + # Sort so that order is not significant + return hash(tuple(parts)) + + +def codes_equal( + code1: Code | CodedConcept, + code2: Code | CodedConcept, + *, + ignore_modifiers: bool = False, +) -> bool: + """Determine whether two codes represent the same concept. + + Unlike the ``==`` operator, this function is symmetric in its arguments + in all situations, including when one argument is a + :class:`pydicom.sr.coding.Code` and the other is a code with modifiers + (see :ref:`coding-gotcha`). It is therefore the safest way to compare codes + when modifiers may be present. + + Two codes are considered equal if their root codes are equivalent (the + same coding scheme designator, code value and coding scheme version; + meanings are not compared, and equivalent SRT and SCT codes are treated as + equal) and, unless `ignore_modifiers` is ``True``, they have the same set + of modifiers (in any order). A code that does not support modifiers, such + as a plain :class:`pydicom.sr.coding.Code`, is treated as having no + modifiers. The class of the codes is not considered. + + Parameters + ---------- + code1: pydicom.sr.coding.Code | highdicom.sr.CodedConcept + First code to compare. May be an instance of a class that has + modifiers, such as :class:`highdicom.seg.SegmentedPropertyType`. + code2: pydicom.sr.coding.Code | highdicom.sr.CodedConcept + Second code to compare. + ignore_modifiers: bool, optional + If True, only the root codes are compared, and any modifiers are + disregarded. + + Returns + ------- + bool + True if the two codes are considered equal, False otherwise. + + Raises + ------ + TypeError + If either argument is not a ``pydicom.sr.coding.Code`` or + :class:`highdicom.sr.CodedConcept`. + + """ + for name, code in [('code1', code1), ('code2', code2)]: + if not isinstance(code, (Code, CodedConcept)): + raise TypeError( + f"Argument '{name}' must be either pydicom.sr.coding.Code or " + "highdicom.sr.CodedConcept." + ) + + root1 = Code( + code1.value, + code1.scheme_designator, + code1.meaning, + code1.scheme_version, + ) + if not Code.__eq__(root1, code2): + return False + + if ignore_modifiers: + return True + + modifiers1 = list(getattr(code1, 'modifiers', ())) + modifiers2 = list(getattr(code2, 'modifiers', ())) + + if len(modifiers1) != len(modifiers2): + return False + + # Match modifiers irrespective of order. Pairwise matching rather than + # sorting is used since equivalent codes (e.g. SRT and SCT) may sort + # differently. + for mod1 in modifiers1: + for i, mod2 in enumerate(modifiers2): + if codes_equal(mod1, mod2): + del modifiers2[i] + break + else: + return False + + return True diff --git a/src/highdicom/sr/sop.py b/src/highdicom/sr/sop.py index 551f194cc..2044e9682 100644 --- a/src/highdicom/sr/sop.py +++ b/src/highdicom/sr/sop.py @@ -179,17 +179,6 @@ def __init__( manufacturer=manufacturer, modality='SR', transfer_syntax_uid=transfer_syntax_uid, - patient_id=evidence[0].PatientID, - patient_name=evidence[0].PatientName, - patient_birth_date=evidence[0].PatientBirthDate, - patient_sex=evidence[0].PatientSex, - accession_number=evidence[0].AccessionNumber, - study_id=evidence[0].StudyID, - study_date=evidence[0].StudyDate, - study_time=evidence[0].StudyTime, - referring_physician_name=getattr( - evidence[0], 'ReferringPhysicianName', None - ), specific_character_set=specific_character_set, **kwargs ) diff --git a/src/highdicom/sr/templates.py b/src/highdicom/sr/templates.py index b7f7a126b..a078f47db 100644 --- a/src/highdicom/sr/templates.py +++ b/src/highdicom/sr/templates.py @@ -2378,7 +2378,8 @@ class QualitativeEvaluation(Template): def __init__( self, name: Code | CodedConcept, - value: Code | CodedConcept + value: Code | CodedConcept, + modifiers: Sequence[CodeContentItem] | None = None, ) -> None: """ Parameters @@ -2387,6 +2388,16 @@ def __init__( concept name value: Union[highdicom.sr.CodedConcept, pydicom.sr.coding.Code] coded value or an enumerated item representing a coded value + modifiers: Sequence[highdicom.sr.CodeContentItem] | None, optional + Further codes that modify the main "value" code, provided as a + sequence of :class:`highdicom.sr.CodeContentItem`. The + ``relationship_type`` of each item must be "HAS CONCEPT MOD" or not + specified, in which case it will be set to "HAS CONCEPT MOD" + automatically. Any other ``relationship_type`` will lead to a + ``ValueError``. See :dcm:`CID 210 Qualitative Evaluation Modifier + Type ` for the context group for the code + names, and :dcm:`CID 211 Qualitative Evaluation Modifier Value + ` for the code values. """ # noqa: E501 item = CodeContentItem( @@ -2394,6 +2405,33 @@ def __init__( value=value, relationship_type=RelationshipTypeValues.CONTAINS ) + if modifiers is not None and len(modifiers) > 0: + content = [] + for modifier in modifiers: + if not isinstance(modifier, CodeContentItem): + raise TypeError( + "Items of 'modifiers' must have type " + "highdicom.sr.CodeContentItem." + ) + + if 'RelationshipType' not in modifier: + modifier.RelationshipType = ( + RelationshipTypeValues.HAS_CONCEPT_MOD.value + ) + + elif ( + modifier.relationship_type != + RelationshipTypeValues.HAS_CONCEPT_MOD + ): + raise ValueError( + "Items of 'modifiers' must have relationship type " + "'HAS CONCEPT MOD'." + ) + + content.append(modifier) + + item.ContentSequence = content + super().__init__([item]) @classmethod @@ -2424,7 +2462,18 @@ def from_sequence( 'Qualitative Evaluation shall contain only one content item.' ) item = CodeContentItem.from_dataset(sequence[0]) - return cls(name=item.name, value=item.value) + + # Only CODE items with relationship type HAS CONCEPT MOD are + # recognized as modifiers. Any other child content items are not + # part of this template and are discarded + modifiers = [ + modifier for modifier in getattr(item, 'ContentSequence', []) + if isinstance(modifier, CodeContentItem) and + modifier.relationship_type == + RelationshipTypeValues.HAS_CONCEPT_MOD + ] + + return cls(name=item.name, value=item.value, modifiers=modifiers) @property def name(self) -> CodedConcept: @@ -2432,8 +2481,104 @@ def name(self) -> CodedConcept: return self[0].name @property - def value(self) -> int | float: - """Union[int, float]: coded value of the qualitative evaluation""" + def value(self) -> CodedConcept: + """highdicom.sr.CodedConcept: coded value of the qualitative + evaluation""" + return self[0].value + + @property + def modifiers(self) -> list[CodeContentItem]: + """list[highdicom.sr.CodeContentItem]: content items that modify the + value of the qualitative evaluation (empty list if there are none)""" + if not hasattr(self[0], 'ContentSequence'): + return [] + + return [ + item for item in self[0].ContentSequence + if isinstance(item, CodeContentItem) and + item.relationship_type == + RelationshipTypeValues.HAS_CONCEPT_MOD + ] + + +class TextEvaluation(Template): + + """Qualitative evaluation with a free text value. + + This may be used to make evaluations of measurement groups using free text, + unlike :class:`highdicom.sr.QualitativeEvaluation`, which has a coded + value. It is recommended to use coded evaluations preferentially to free + text evaluations as they are standardized and leave less room for ambiguity. + + This corresponds to the TEXT content item of a qualitative evaluation + within a measurement group, e.g. row 12 of :dcm:`TID 1501 + `, row 13 of :dcm:`TID 1410 + `, and row 17 of :dcm:`TID 1411 + `. Unlike a + :class:`highdicom.sr.QualitativeEvaluation`, a text evaluation may not + have modifiers. + + """ + + def __init__( + self, + name: Code | CodedConcept, + value: str, + ) -> None: + """ + Parameters + ---------- + name: Union[highdicom.sr.CodedConcept, pydicom.sr.coding.Code] + Concept name of the evaluation + value: str + Free text value of the evaluation + + """ # noqa: E501 + item = TextContentItem( + name=name, + value=value, + relationship_type=RelationshipTypeValues.CONTAINS + ) + super().__init__([item]) + + @classmethod + def from_sequence( + cls, + sequence: Sequence[Dataset], + is_root: bool = False + ) -> Self: + """Construct object from a sequence of content items. + + Parameters + ---------- + sequence: Sequence[pydicom.dataset.Dataset] + Content Sequence containing one SR TEXT Content Item + is_root: bool, optional + Whether the sequence is used to contain SR Content Items that are + intended to be added to an SR document at the root of the document + content tree + + Returns + ------- + highdicom.sr.TextEvaluation + Content Sequence containing one SR TEXT Content Item + + """ + if len(sequence) > 1: + raise ValueError( + 'Text Evaluation shall contain only one content item.' + ) + item = TextContentItem.from_dataset(sequence[0]) + return cls(name=item.name, value=item.value) + + @property + def name(self) -> CodedConcept: + """highdicom.sr.CodedConcept: name of the text evaluation""" + return self[0].name + + @property + def value(self) -> str: + """str: free text value of the text evaluation""" return self[0].value @@ -2780,6 +2925,7 @@ def __init__( Sequence[QualitativeEvaluation] ) = None, finding_category: CodedConcept | Code | None = None, + text_evaluations: Sequence[TextEvaluation] | None = None, ): """ @@ -2812,6 +2958,9 @@ def __init__( finding_category: Union[highdicom.sr.CodedConcept, pydicom.sr.coding.Code, None], optional Category of observed finding, e.g., anatomic structure or morphologically abnormal structure + text_evaluations: Union[Sequence[highdicom.sr.TextEvaluation], None], optional + Name-value pairs with coded names and free text values that + describe qualitative evaluations. """ # noqa: E501 super().__init__() @@ -2932,6 +3081,14 @@ def __init__( 'have type QualitativeEvaluation.' ) content.extend(evaluation) + if text_evaluations is not None: + for text_evaluation in text_evaluations: + if not isinstance(text_evaluation, TextEvaluation): + raise TypeError( + 'Items of argument "text_evaluations" must ' + 'have type TextEvaluation.' + ) + content.extend(text_evaluation) if len(content) > 0: group_item.ContentSequence = content self.append(group_item) @@ -3162,6 +3319,43 @@ def get_qualitative_evaluations( ) ] + def get_text_evaluations( + self, + name: Code | CodedConcept | None = None + ) -> list[TextEvaluation]: + """Get text evaluations. + + Parameters + ---------- + name: Union[pydicom.sr.coding.Code, highdicom.sr.CodedConcept, None], optional + Name used to filter evaluations. If ``None``, all evaluations found + are returned. + + Returns + ------- + List[highdicom.sr.TextEvaluation] + Text evaluations + + """ # noqa: E501 + root_item = self[0] + # Other TEXT content items in the measurement group (e.g., tracking + # identifier, session, time point context, algorithm identification) + # use relationship types other than CONTAINS + if name is None: + matches = find_content_items( + root_item, + value_type=ValueTypeValues.TEXT, + relationship_type=RelationshipTypeValues.CONTAINS, + ) + else: + matches = find_content_items( + root_item, + name=name, + value_type=ValueTypeValues.TEXT, + relationship_type=RelationshipTypeValues.CONTAINS, + ) + return [TextEvaluation.from_sequence([item]) for item in matches] + class MeasurementsAndQualitativeEvaluations( _MeasurementsAndQualitativeEvaluations @@ -3188,6 +3382,7 @@ def __init__( source_images: None | ( Sequence[SourceImageForMeasurementGroup] ) = None, + text_evaluations: Sequence[TextEvaluation] | None = None, ): """ @@ -3224,6 +3419,9 @@ def __init__( Images to that were the source of the measurements. If not provided, all images that listed in the document tree of the containing SR document are assumed to be source images. + text_evaluations: Union[Sequence[highdicom.sr.TextEvaluation], None], optional + Name-value pairs with coded names and free text values that + describe qualitative evaluations """ # noqa: E501 super().__init__( @@ -3238,6 +3436,7 @@ def __init__( measurements=measurements, qualitative_evaluations=qualitative_evaluations, finding_category=finding_category, + text_evaluations=text_evaluations, ) group_item = self[0] @@ -3309,6 +3508,7 @@ def __init__( ) = None, geometric_purpose: CodedConcept | Code | None = None, finding_category: CodedConcept | Code | None = None, + text_evaluations: Sequence[TextEvaluation] | None = None, ): """ @@ -3352,6 +3552,9 @@ def __init__( finding_category: Union[highdicom.sr.CodedConcept, pydicom.sr.coding.Code, None], optional Category of observed finding, e.g., anatomic structure or morphologically abnormal structure + text_evaluations: Union[Sequence[highdicom.sr.TextEvaluation], None], optional + Name-value pairs with coded names and free text values that + describe qualitative evaluations Note ---- @@ -3371,7 +3574,8 @@ def __init__( session=session, measurements=measurements, qualitative_evaluations=qualitative_evaluations, - finding_category=finding_category + finding_category=finding_category, + text_evaluations=text_evaluations, ) group_item = self[0] were_references_provided = [ @@ -3471,7 +3675,8 @@ def __init__( Sequence[QualitativeEvaluation] ) = None, geometric_purpose: CodedConcept | Code | None = None, - finding_category: CodedConcept | Code | None = None + finding_category: CodedConcept | Code | None = None, + text_evaluations: Sequence[TextEvaluation] | None = None, ): """ @@ -3513,6 +3718,9 @@ def __init__( finding_category: Union[highdicom.sr.CodedConcept, pydicom.sr.coding.Code, None], optional Category of observed finding, e.g., anatomic structure or morphologically abnormal structure + text_evaluations: Union[Sequence[highdicom.sr.TextEvaluation], None], optional + Name-value pairs with coded names and free text values that + describe qualitative evaluations of a region of interest Note ---- @@ -3569,7 +3777,8 @@ def __init__( measurements=measurements, qualitative_evaluations=qualitative_evaluations, geometric_purpose=geometric_purpose, - finding_category=finding_category + finding_category=finding_category, + text_evaluations=text_evaluations, ) self[0].ContentTemplateSequence[0].TemplateIdentifier = '1410' @@ -3756,6 +3965,7 @@ def __init__( ) = None, geometric_purpose: CodedConcept | Code | None = None, finding_category: CodedConcept | Code | None = None, + text_evaluations: Sequence[TextEvaluation] | None = None, ): """ @@ -3799,6 +4009,9 @@ def __init__( finding_category: Union[highdicom.sr.CodedConcept, pydicom.sr.coding.Code, None], optional Category of observed finding, e.g., anatomic structure or morphologically abnormal structure + text_evaluations: Union[Sequence[highdicom.sr.TextEvaluation], None], optional + Name-value pairs with coded names and free text values that + describe qualitative evaluations of a volume of interest Note ---- @@ -3839,7 +4052,8 @@ def __init__( session=session, qualitative_evaluations=qualitative_evaluations, geometric_purpose=geometric_purpose, - finding_category=finding_category + finding_category=finding_category, + text_evaluations=text_evaluations, ) self[0].ContentTemplateSequence[0].TemplateIdentifier = '1411' diff --git a/src/highdicom/version.py b/src/highdicom/version.py index 873054ed2..9093e4e46 100644 --- a/src/highdicom/version.py +++ b/src/highdicom/version.py @@ -1 +1 @@ -__version__ = '0.28.2' +__version__ = '0.29.0' diff --git a/src/highdicom/volume.py b/src/highdicom/volume.py index fc50f8b41..507646fcd 100644 --- a/src/highdicom/volume.py +++ b/src/highdicom/volume.py @@ -22,6 +22,7 @@ PATIENT_ORIENTATION_OPPOSITES, VOLUME_INDEX_CONVENTION, _DEFAULT_EQUALITY_TOLERANCE, + _DEFAULT_PERPENDICULAR_TOLERANCE, _is_matrix_orthogonal, _normalize_patient_orientation, _stack_affine_matrix, @@ -1789,7 +1790,10 @@ def match_geometry( mode: PadModes = PadModes.CONSTANT, constant_value: float = 0.0, per_channel: bool = False, - tol: float = _DEFAULT_EQUALITY_TOLERANCE, + spacing_tol: float = 1e-3, + position_tol: float = 1e-2, + parallel_tol: float = _DEFAULT_PERPENDICULAR_TOLERANCE, + tol: float | None = None, ) -> Self: """Match the geometry of this volume to another. @@ -1817,6 +1821,24 @@ def match_geometry( the entire array). For other padding modes, this argument makes no difference. This should be True only if the volume has a channel dimension. + spacing_tol: float, optional + Relative tolerance on the ratio of the voxel spacing of ``other`` + to that of this volume along each axis. The ratio must be within + ``spacing_tol * n`` of the nearest integer ``n``, i.e. the + tolerance scales with the integer step size. + position_tol: float, optional + Tolerance on the translation between the two volumes along each + axis, expressed as a fraction of a voxel (of this volume, after + permutation). The translation must be within this fraction of an + integer number of voxels. The same tolerance is applied to the + misalignment at the far end of the target grid, which accumulates + any small spacing discrepancy over the extent of the volume. + parallel_tol: float, optional + Tolerance used when deciding whether direction vectors of the two + volumes are parallel. + tol: float | None, optional + Deprecated. If provided, it overrides both ``spacing_tol`` and + ``position_tol``. Use those parameters instead. Returns ------- @@ -1830,14 +1852,25 @@ def match_geometry( If the geometries cannot be matched without resampling the array. """ + if tol is not None: + warnings.warn( + "The 'tol' parameter of 'match_geometry' is deprecated and " + "will be removed in a future release. Use 'spacing_tol' and " + "'position_tol' instead.", + DeprecationWarning, + stacklevel=2, + ) + spacing_tol = tol + position_tol = tol + if ( self.frame_of_reference_uid is not None and - other.frame_of_reference_uid is not None + other.frame_of_reference_uid is not None and + self.frame_of_reference_uid != other.frame_of_reference_uid ): - if self.frame_of_reference_uid != self.frame_of_reference_uid: - raise RuntimeError( - "Volumes do not have matching frame of reference UIDs." - ) + raise RuntimeError( + "Volumes do not have matching frame of reference UIDs." + ) if self.coordinate_system != other.coordinate_system: raise RuntimeError( @@ -1846,28 +1879,31 @@ def match_geometry( permute_indices = [] step_sizes = [] + signed_scale_factors = [] for u, s in zip(other.unit_vectors(), other.spacing): for j, (v, t) in enumerate( zip(self.unit_vectors(), self.spacing) ): dot_product = u @ v if ( - np.abs(dot_product - 1.0) < tol or - np.abs(dot_product + 1.0) < tol + np.abs(dot_product - 1.0) < parallel_tol or + np.abs(dot_product + 1.0) < parallel_tol ): permute_indices.append(j) scale_factor = s / t step = int(np.round(scale_factor)) - if abs(scale_factor - step) > tol: + if abs(scale_factor - step) > spacing_tol * abs(step): raise RuntimeError( "Non-integer scale factor required." ) if dot_product < 0.0: step = -step + scale_factor = -scale_factor step_sizes.append(step) + signed_scale_factors.append(scale_factor) break else: @@ -1892,10 +1928,11 @@ def match_geometry( requires_crop = False requires_pad = False - for v, spacing, step, out_shape, in_shape in zip( + for v, spacing, step, scale_factor, out_shape, in_shape in zip( new_volume.unit_vectors(), new_volume.spacing, step_sizes, + signed_scale_factors, other.spatial_shape, new_volume.spatial_shape, ): @@ -1904,12 +1941,25 @@ def match_geometry( start_pos = int(np.round(start_ind)) end_pos = start_pos + out_shape * step - if abs(start_pos - start_ind) > tol: + if abs(start_pos - start_ind) > position_tol: raise RuntimeError( "Required translation is non-integer " "multiple of voxel spacing." ) + # Small spacing discrepancies accumulate along the axis, so also + # check the misalignment at the far end of the target grid + far_misalignment = ( + (start_ind - start_pos) + + (out_shape - 1) * (scale_factor - step) + ) + if abs(far_misalignment) > position_tol: + raise RuntimeError( + "Voxel grids drift out of alignment by more than " + "'position_tol' along an axis due to a small difference " + "in spacing." + ) + if step > 0: pad_before = max(-start_pos, 0) pad_after = max(end_pos - in_shape, 0) diff --git a/tests/test_ann.py b/tests/test_ann.py index 432d17f21..3d3a0957d 100644 --- a/tests/test_ann.py +++ b/tests/test_ann.py @@ -9,7 +9,12 @@ from pydicom.sr.codedict import codes from pydicom.sr.coding import Code -from highdicom.ann.content import Measurements, AnnotationGroup +from highdicom import AnatomicRegion, PrimaryAnatomicStructure +from highdicom.ann.content import ( + AnnotatedPropertyType, + AnnotationGroup, + Measurements, +) from highdicom.ann.enum import ( AnnotationCoordinateTypeValues, AnnotationGroupGenerationTypeValues, @@ -379,6 +384,7 @@ def test_alternative_construction_from_dataset(self): assert group.algorithm_identification is None assert isinstance(group.annotated_property_category, CodedConcept) assert isinstance(group.annotated_property_type, CodedConcept) + assert isinstance(group.annotated_property_type, AnnotatedPropertyType) graphic_data = group.get_graphic_data( coordinate_type=AnnotationCoordinateTypeValues.SCOORD @@ -400,6 +406,115 @@ def test_alternative_construction_from_dataset(self): assert values.dtype == np.float32 assert values.shape == (3, 0) + def _make_group(self, **kwargs): + args = dict( + number=1, + uid=UID(), + label='group', + annotated_property_category=self._property_category, + annotated_property_type=self._property_type, + graphic_type=GraphicTypeValues.POINT, + graphic_data=[np.array([[1.0, 2.0, 0.0]])], + algorithm_type=self._algorithm_type, + algorithm_identification=self._algorithm_identification, + ) + args.update(kwargs) + return AnnotationGroup(**args) + + def test_modified_codes_plain_codes_converted(self): + group = self._make_group( + anatomic_regions=[self._anatomic_region], + primary_anatomic_structures=[self._anatomic_structure], + ) + assert isinstance(group.annotated_property_type, AnnotatedPropertyType) + assert group.annotated_property_type.modifiers == () + assert isinstance(group.anatomic_regions[0], AnatomicRegion) + assert isinstance( + group.primary_anatomic_structures[0], PrimaryAnatomicStructure + ) + assert group.annotated_property_type == self._property_type + + def test_modified_codes_with_modifiers(self): + group = self._make_group( + annotated_property_type=AnnotatedPropertyType( + self._property_type, modifiers=[codes.SCT.Left] + ), + anatomic_regions=[ + AnatomicRegion(codes.SCT.Thorax, modifiers=[codes.SCT.Right]), + codes.SCT.Abdomen, + ], + primary_anatomic_structures=[ + PrimaryAnatomicStructure( + codes.SCT.Lung, modifiers=[codes.SCT.Left] + ), + ], + ) + ptype = group.annotated_property_type + assert ptype.modifiers == (codes.SCT.Left, ) + assert ptype.unmodified == self._property_type + assert len( + group.AnnotationPropertyTypeCodeSequence[0] + .AnnotationPropertyTypeModifierCodeSequence + ) == 1 + assert group.anatomic_regions[0].modifiers == (codes.SCT.Right, ) + assert group.anatomic_regions[1].modifiers == () + assert len( + group.AnatomicRegionSequence[0].AnatomicRegionModifierSequence + ) == 1 + assert group.primary_anatomic_structures[0].modifiers == ( + codes.SCT.Left, + ) + + def test_modified_codes_wrong_types(self): + with pytest.raises(TypeError): + self._make_group( + annotated_property_category=AnnotatedPropertyType( + self._property_category + ) + ) + with pytest.raises(TypeError): + self._make_group( + annotated_property_type=AnatomicRegion(self._property_type) + ) + with pytest.raises(TypeError): + self._make_group( + anatomic_regions=[PrimaryAnatomicStructure(codes.SCT.Lung)] + ) + with pytest.raises(TypeError): + self._make_group( + primary_anatomic_structures=[AnatomicRegion(codes.SCT.Lung)] + ) + + def test_modified_codes_from_dataset_round_trip(self): + group = self._make_group( + annotated_property_type=AnnotatedPropertyType( + self._property_type, modifiers=[codes.SCT.Left] + ), + anatomic_regions=[ + AnatomicRegion(codes.SCT.Thorax, modifiers=[codes.SCT.Right]), + ], + primary_anatomic_structures=[ + PrimaryAnatomicStructure( + codes.SCT.Lung, modifiers=[codes.SCT.Left] + ), + ], + ) + ds = Dataset() + ds.AnnotationGroupSequence = [group] + ds = write_and_read_dataset(ds) + read = AnnotationGroup.from_dataset(ds.AnnotationGroupSequence[0]) + + assert isinstance(read.annotated_property_type, AnnotatedPropertyType) + assert read.annotated_property_type.modifiers == (codes.SCT.Left, ) + assert isinstance(read.anatomic_regions[0], AnatomicRegion) + assert read.anatomic_regions[0].modifiers == (codes.SCT.Right, ) + assert isinstance( + read.primary_anatomic_structures[0], PrimaryAnatomicStructure + ) + assert read.primary_anatomic_structures[0].modifiers == ( + codes.SCT.Left, + ) + def test_alternative_construction_from_dataset_missing_attributes(self): dataset = Dataset() with pytest.raises(AttributeError): @@ -687,3 +802,167 @@ def test_construction(self, annotation_coordinate_type): assert isinstance(retrieved_group, AnnotationGroup) assert retrieved_group.number == 1 assert retrieved_group.label == first_label + + def _modified_type_annotations(self): + """Annotations with groups whose property types have modifiers. + + Group 1: Cell (no modifiers) + Group 2: Cell + Left + Group 3: Cell + Left + Posterior + Group 4: Nucleus + Left + """ + category = Code('91723000', 'SCT', 'Anatomical Structure') + cell = Code('4421005', 'SCT', 'Cell') + nucleus = Code('84640000', 'SCT', 'Nucleus') + types = [ + cell, + AnnotatedPropertyType(cell, modifiers=[codes.SCT.Left]), + AnnotatedPropertyType( + cell, modifiers=[codes.SCT.Left, codes.SCT.Posterior] + ), + AnnotatedPropertyType(nucleus, modifiers=[codes.SCT.Left]), + ] + groups = [ + AnnotationGroup( + number=i + 1, + uid=UID(), + label=f'group{i + 1}', + annotated_property_category=category, + annotated_property_type=ptype, + graphic_type=GraphicTypeValues.POINT, + graphic_data=[np.array([[1.0, 2.0]])], + algorithm_type=AnnotationGroupGenerationTypeValues.MANUAL, + ) + for i, ptype in enumerate(types) + ] + annotations = MicroscopyBulkSimpleAnnotations( + source_images=[self._sm_image], + annotation_coordinate_type=AnnotationCoordinateTypeValues.SCOORD, + annotation_groups=groups, + series_instance_uid=UID(), + series_number=2, + sop_instance_uid=UID(), + instance_number=1, + manufacturer='highdicom', + manufacturer_model_name='test', + software_versions='0.1.0rc', + device_serial_number='XYZ' + ) + # Round trip so that parsing is covered too + with BytesIO() as fp: + annotations.save_as(fp) + fp.seek(0) + return annread(fp) + + @staticmethod + def _numbers(groups): + return [g.number for g in groups] + + def test_get_annotation_groups_plain_code_ignores_modifiers(self): + annotations = self._modified_type_annotations() + for query in [ + codes.SCT.Cell, + CodedConcept.from_code(codes.SCT.Cell), + ]: + groups = annotations.get_annotation_groups( + annotated_property_type=query + ) + assert self._numbers(groups) == [1, 2, 3] + + groups = annotations.get_annotation_groups( + annotated_property_type=codes.SCT.Nucleus, + ) + assert self._numbers(groups) == [4] + + groups = annotations.get_annotation_groups( + annotated_property_type=Code('53982002', 'SCT', 'Cell membrane') + ) + assert groups == [] + + def test_get_annotation_groups_modified_type_no_modifiers(self): + annotations = self._modified_type_annotations() + groups = annotations.get_annotation_groups( + annotated_property_type=AnnotatedPropertyType( + codes.SCT.Cell, + ) + ) + assert self._numbers(groups) == [1] + + def test_get_annotation_groups_modified_type_modifiers(self): + annotations = self._modified_type_annotations() + cell = codes.SCT.Cell + + groups = annotations.get_annotation_groups( + annotated_property_type=AnnotatedPropertyType( + cell, modifiers=[codes.SCT.Left] + ) + ) + assert self._numbers(groups) == [2] + + # Order of modifiers is not significant + for modifiers in ( + [codes.SCT.Left, codes.SCT.Posterior], + [codes.SCT.Posterior, codes.SCT.Left], + ): + groups = annotations.get_annotation_groups( + annotated_property_type=AnnotatedPropertyType( + cell, modifiers=modifiers + ) + ) + assert self._numbers(groups) == [3] + + def test_get_annotation_groups_modified_type_no_match(self): + annotations = self._modified_type_annotations() + cell = codes.SCT.Cell + + # Modifier not present on any group + assert annotations.get_annotation_groups( + annotated_property_type=AnnotatedPropertyType( + cell, modifiers=[codes.SCT.Right] + ) + ) == [] + # Superset of a group's modifiers + assert annotations.get_annotation_groups( + annotated_property_type=AnnotatedPropertyType( + cell, + modifiers=[ + codes.SCT.Left, codes.SCT.Posterior, codes.SCT.Right + ], + ) + ) == [] + # Wrong root code + assert annotations.get_annotation_groups( + annotated_property_type=AnnotatedPropertyType( + Code('53982002', 'SCT', 'Cell membrane'), + modifiers=[codes.SCT.Left], + ) + ) == [] + + def test_get_annotation_groups_modified_type_combined_filters(self): + annotations = self._modified_type_annotations() + nucleus = Code('84640000', 'SCT', 'Nucleus') + groups = annotations.get_annotation_groups( + annotated_property_category=codes.SCT.AnatomicalStructure, + annotated_property_type=AnnotatedPropertyType( + nucleus, modifiers=[codes.SCT.Left] + ), + graphic_type=GraphicTypeValues.POINT, + ) + assert self._numbers(groups) == [4] + + groups = annotations.get_annotation_groups( + annotated_property_type=AnnotatedPropertyType( + nucleus, modifiers=[codes.SCT.Left] + ), + label='group1', + ) + assert groups == [] + + def test_parsed_groups_have_modified_types(self): + annotations = self._modified_type_annotations() + for group in annotations.get_annotation_groups(): + assert isinstance( + group.annotated_property_type, AnnotatedPropertyType + ) + group = annotations.get_annotation_group(number=3) + assert len(group.annotated_property_type.modifiers) == 2 diff --git a/tests/test_base.py b/tests/test_base.py index 905a0f08b..a18b33364 100644 --- a/tests/test_base.py +++ b/tests/test_base.py @@ -4,6 +4,7 @@ import unittest from pydicom import dcmread +from pydicom.dataset import Dataset from pydicom.uid import ( ExplicitVRBigEndian, ExplicitVRLittleEndian, @@ -11,6 +12,7 @@ ) from pydicom.data import get_testdata_file from highdicom import SOPClass, UID +from highdicom.coding_schemes import CodingSchemeIdentificationItem from highdicom.base import _check_little_endian from highdicom.enum import SpecificCharacterSetValues @@ -65,6 +67,7 @@ def test_type_3_attributes(self): assert hasattr(instance, 'ContentTime') assert not hasattr(instance, 'SeriesDate') assert not hasattr(instance, 'SeriesTime') + assert 'CodingSchemeIdentificationSequence' not in instance def test_content_time_without_date(self): msg = ( @@ -398,6 +401,65 @@ def test_specific_character_invalid_multivalue(self): ] ) + def test_coding_schemes(self): + items = [ + CodingSchemeIdentificationItem( + designator='99TEST', + name='Test Scheme', + version='1.0', + ), + CodingSchemeIdentificationItem( + designator='SCT', + registry='HL7', + uid='2.16.840.1.113883.6.96', + ), + ] + instance = SOPClass( + study_instance_uid=UID(), + series_instance_uid=UID(), + series_number=1, + sop_instance_uid=UID(), + sop_class_uid='1.2.840.10008.5.1.4.1.1.88.33', + instance_number=1, + modality='SR', + manufacturer='highdicom', + coding_schemes=items, + ) + seq = instance.CodingSchemeIdentificationSequence + assert len(seq) == 2 + assert seq[0].CodingSchemeDesignator == '99TEST' + assert seq[0].CodingSchemeName == 'Test Scheme' + assert seq[1].CodingSchemeDesignator == 'SCT' + assert seq[1].CodingSchemeUID == '2.16.840.1.113883.6.96' + + def test_coding_schemes_empty(self): + instance = SOPClass( + study_instance_uid=UID(), + series_instance_uid=UID(), + series_number=1, + sop_instance_uid=UID(), + sop_class_uid='1.2.840.10008.5.1.4.1.1.88.33', + instance_number=1, + modality='SR', + manufacturer='highdicom', + coding_schemes=[], + ) + assert 'CodingSchemeIdentificationSequence' not in instance + + def test_coding_schemes_wrong_type(self): + with pytest.raises(TypeError): + SOPClass( + study_instance_uid=UID(), + series_instance_uid=UID(), + series_number=1, + sop_instance_uid=UID(), + sop_class_uid='1.2.840.10008.5.1.4.1.1.88.33', + instance_number=1, + modality='SR', + manufacturer='highdicom', + coding_schemes=[Dataset()], + ) + class TestEndianCheck(unittest.TestCase): diff --git a/tests/test_color.py b/tests/test_color.py index acff5644e..5a6e98d7a 100644 --- a/tests/test_color.py +++ b/tests/test_color.py @@ -4,7 +4,17 @@ import pytest from PIL.ImageCms import ImageCmsProfile, createProfile -from highdicom.color import ColorManager, CIELabColor +from highdicom.color import ( + _D50_WHITEPOINT_X, + _D50_WHITEPOINT_Y, + _D50_WHITEPOINT_Z, + _lab_to_rgb, + _rgb_to_lab, + _rgb_to_xyz, + _xyz_to_rgb, + CIELabColor, + ColorManager, +) @pytest.mark.parametrize( @@ -24,18 +34,21 @@ def test_cielab(l_in, a_in, b_in, out): @pytest.mark.parametrize( - # Examples generated from colormine.org + # Expected values are CIELab relative to the D50 white point (the + # illuminant of the ICC Profile Connection Space, which is what DICOM + # uses), as produced by the sample code of the CSS Color Module Level 4 + # and by DCMTK's IODCIELabUtil 'r,g,b,l_out,a_out,b_out', [ [0, 0, 0, 0.0, 0.0, 0.0], - [255, 0, 0, 53.23, 80.11, 67.22], - [0, 255, 0, 87.74, -86.18, 83.18], - [0, 0, 255, 32.30, 79.20, -107.86], - [0, 255, 255, 91.11, -48.08, -14.14], - [255, 255, 0, 97.14, -21.56, 94.48], - [255, 0, 255, 60.32, 98.25, -60.84], - [255, 255, 255, 100.0, 0.0, -0.01], - [45, 123, 198, 50.45, 2.59, -45.75], + [255, 0, 0, 54.291, 80.805, 69.891], + [0, 255, 0, 87.819, -79.271, 80.995], + [0, 0, 255, 29.568, 68.287, -112.030], + [0, 255, 255, 90.666, -50.656, -14.962], + [255, 255, 0, 97.607, -15.750, 93.394], + [255, 0, 255, 60.169, 93.540, -60.501], + [255, 255, 255, 100.0, 0.0, 0.0], + [45, 123, 198, 49.75, -3.84, -46.70], ] ) def test_from_rgb(r, g, b, l_out, a_out, b_out): @@ -63,7 +76,7 @@ def test_to_rgb_invalid(): # With clip=True, will clip to closest representable value r, g, b = color.to_rgb(clip=True) assert r == 255 - assert g == 125 + assert g == 107 assert b == 255 @@ -113,6 +126,142 @@ def test_cielab_invalid(l_in, a_in, b_in): CIELabColor(l_in, a_in, b_in) +# Reference colors used by DCMTK's test suite for IODCIELabUtil: sRGB (8 bit) +# and the corresponding D50 CIELab (ICC PCS) values, as computed by the sample +# code of the CSS Color Module Level 4. The first part are CSS named colors, +# the second part are colors from 3D Slicer's "General Anatomy" color table. +REFERENCE_COLORS = [ + ('black', 0, 0, 0, 0.000, 0.000, 0.000), + ('white', 255, 255, 255, 100.000, 0.000, 0.000), + ('gray', 128, 128, 128, 53.585, 0.000, 0.000), + ('silver', 192, 192, 192, 77.704, 0.000, 0.000), + ('red', 255, 0, 0, 54.291, 80.805, 69.891), + ('lime', 0, 255, 0, 87.819, -79.271, 80.995), + ('blue', 0, 0, 255, 29.568, 68.287, -112.030), + ('yellow', 255, 255, 0, 97.607, -15.750, 93.394), + ('cyan', 0, 255, 255, 90.666, -50.656, -14.962), + ('magenta', 255, 0, 255, 60.169, 93.540, -60.501), + ('maroon', 128, 0, 0, 26.165, 48.473, 39.439), + ('navy', 0, 0, 128, 11.335, 40.964, -67.203), + ('olive', 128, 128, 0, 52.150, -9.448, 56.024), + ('teal', 0, 128, 128, 47.986, -30.387, -8.975), + ('purple', 128, 0, 128, 29.692, 56.112, -36.293), + ('orange', 255, 165, 0, 75.590, 27.516, 79.121), + ('cornflowerblue', 100, 149, 237, 61.233, 3.047, -50.188), + ('darkslategray', 47, 79, 79, 31.141, -12.261, -3.937), + ('hotpink', 255, 105, 180, 65.860, 63.258, -9.644), + ('indigo', 75, 0, 130, 19.715, 47.029, -54.278), + ('lavender', 230, 230, 250, 91.742, 2.775, -9.724), + ('midnightblue', 25, 25, 112, 14.929, 25.955, -50.904), + ('peru', 205, 133, 63, 62.253, 23.948, 48.413), + ('springgreen', 0, 255, 127, 88.436, -72.499, 45.977), + ('CSF space', 85, 188, 255, 72.318, -15.277, -42.679), + ('aorta', 224, 97, 76, 57.648, 49.583, 37.620), + ('bile', 0, 145, 30, 52.261, -51.068, 46.791), + ('bone', 241, 214, 145, 86.748, 2.835, 37.696), + ('brain', 250, 250, 225, 97.780, -3.106, 12.048), + ('capillary', 183, 156, 220, 68.539, 19.645, -28.946), + ('cartilage', 111, 184, 210, 70.737, -18.519, -20.706), + ('gray matter', 200, 200, 235, 81.452, 5.183, -17.387), + ('liver', 221, 130, 101, 64.063, 33.878, 31.516), + ('muscle', 192, 104, 88, 54.284, 34.766, 25.456), + ('pancreas', 249, 180, 111, 78.903, 20.532, 45.266), + ('skin', 177, 122, 101, 56.608, 20.206, 20.612), + ('spleen', 157, 108, 162, 52.334, 27.009, -21.229), + ('thyroid gland', 62, 162, 114, 59.883, -39.102, 16.066), + ('vein', 0, 151, 206, 57.968, -19.204, -38.353), + ('white matter', 250, 250, 210, 97.515, -4.805, 19.293), +] + + +@pytest.mark.parametrize('name,r,g,b,l_out,a_out,b_out', REFERENCE_COLORS) +def test_reference_colors(name, r, g, b, l_out, a_out, b_out): + # RGB -> CIELab must match the D50 reference values + l_star, a_star, b_star = _rgb_to_lab(r, g, b) + assert abs(l_star - l_out) < 0.03 + assert abs(a_star - a_out) < 0.03 + assert abs(b_star - b_out) < 0.03 + + # The reference values are rounded to 3 decimals, which may shift a + # component that lies exactly on a gamut boundary by one + r_out, g_out, b_out_ = (round(c) for c in _lab_to_rgb(l_out, a_out, b_out)) + assert abs(r_out - r) <= 1 + assert abs(g_out - g) <= 1 + assert abs(b_out_ - b) <= 1 + + +def test_white_point(): + # sRGB white maps exactly onto the D50 white point of the ICC PCS + assert _rgb_to_xyz(255, 255, 255) == pytest.approx( + (_D50_WHITEPOINT_X, _D50_WHITEPOINT_Y, _D50_WHITEPOINT_Z), + abs=1e-9, + ) + assert _rgb_to_lab(255, 255, 255) == pytest.approx((100.0, 0.0, 0.0)) + + # The D50 white point of ICC v4.3 Table 14 maps back onto sRGB white + assert _xyz_to_rgb(0.96422, 1.0, 0.82521) == pytest.approx( + (255.0, 255.0, 255.0), abs=0.1 + ) + + # White and black have the expected DICOM encodings (ICC v4.3 Table 14) + assert CIELabColor.from_rgb(255, 255, 255).value == (0xFFFF, 0x8080, 0x8080) + assert CIELabColor.from_rgb(0, 0, 0).value == (0x0000, 0x8080, 0x8080) + + +@pytest.mark.parametrize( + 'value,rgb_out', + [ + # Values checked against DCMTK (and PixelMed), all of which lie + # marginally outside the sRGB gamut and therefore require clipping + [(35732, 48892, 14692), (181, 82, 255)], + [(0, 0x8000, 0x8000), (0, 0, 1)], + # Saturated blue, slightly outside the sRGB gamut in linear RGB + [(19378, 50557, 3680), (0, 0, 255)], + ] +) +def test_dicom_value_to_rgb_out_of_gamut(value, rgb_out): + color = CIELabColor.from_dicom_value(value) + + with pytest.raises(ValueError): + color.to_rgb() + + assert color.to_rgb(clip=True) == rgb_out + + +@pytest.mark.parametrize( + 'r,g,b', + # Values from DCMTK's (and PixelMed's) test suite + [ + (0, 0, 0), + (255, 0, 0), + (0, 255, 0), + (0, 0, 255), + (255, 255, 0), + (0, 255, 255), + (255, 0, 255), + (255, 255, 255), + (225, 190, 150), + (200, 200, 200), + (128, 174, 128), + (221, 130, 101), + (0x51, 0x5d, 0xe5), + (0x4c, 0x6e, 0xda), + ] +) +def test_rgb_round_trip(r, g, b): + # An 8 bit RGB triple must survive the round trip through the 16 bit + # DICOM CIELab encoding unchanged + assert CIELabColor.from_rgb(r, g, b).to_rgb() == (r, g, b) + + +def test_rgb_round_trip_cube(): + # As above, but for a sample of the whole RGB cube + for r in range(0, 256, 17): + for g in range(0, 256, 17): + for b in range(0, 256, 17): + assert CIELabColor.from_rgb(r, g, b).to_rgb() == (r, g, b) + + class TestColorManager(unittest.TestCase): def setUp(self) -> None: diff --git a/tests/test_content.py b/tests/test_content.py index 8e70b0600..cec54667e 100644 --- a/tests/test_content.py +++ b/tests/test_content.py @@ -28,6 +28,7 @@ PlanePositionSequence, ReferencedImageSequence, RescaleTypeValues, + SegmentedPaletteColorLUT, SpecimenCollection, SpecimenDescription, SpecimenPreparationStep, @@ -874,6 +875,24 @@ def test_construction_patient(self): assert item.ImageOrientationPatient[4] == image_orientation[4] assert item.ImageOrientationPatient[5] == image_orientation[5] + def test_invalid_non_unit(self): + image_orientation = [0.5, 0.5, 0.0, 0.0, 0.0, 1.0] + msg = "Image orientation must contain unit vectors." + with pytest.raises(ValueError, match=msg): + PlaneOrientationSequence( + "PATIENT", + image_orientation, + ) + + def test_invalid_non_orthogonal(self): + image_orientation = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] + msg = "Image orientation must contain two orthogonal vectors." + with pytest.raises(ValueError, match=msg): + PlaneOrientationSequence( + "PATIENT", + image_orientation, + ) + class TestPixelMeasuresSequence(TestCase): @@ -2212,6 +2231,229 @@ def test_construction_8bit(self): with pytest.raises(TypeError): lut.apply(arr, dtype=dtype) + def test_extract_from_dataset(self): + for dtype in [np.uint8, np.uint16]: + for color in ['red', 'green', 'blue']: + lut_data = np.arange(0, 256, dtype=dtype) + first_mapped_value = 0 + lut = PaletteColorLUT(first_mapped_value, lut_data, color=color) + + # Create a "plain" pydicom dataset containing the same + # attributes + ds = Dataset() + + for k, v in lut.items(): + ds[k] = v + + extracted = PaletteColorLUT.extract_from_dataset( + ds, + color=color + ) + assert extracted == lut + assert np.array_equal(lut.lut_data, lut_data) + + +class TestSegmentedPaletteColorLUT(TestCase): + + def test_construction_16bit(self): + segmented_lut_data = np.array( + [ + 0, 3, 4, 5, 6, # literal [4, 5, 6] + 1, 3, 0, # ramp down to zero in 3 steps [4, 2, 0] + 0, 2, 10, 20, # literal [10, 20] + 1, 4, 40, # ramp up to 40 in 4 steps [25, 30, 35, 40] + ], + dtype=np.uint16 + ) + + # The expected expansion of the above + lut_data = np.array( + [4, 5, 6, 4, 2, 0, 10, 20, 25, 30, 35, 40], + dtype=np.uint16, + ) + + first_mapped_value = 32 + lut = SegmentedPaletteColorLUT( + first_mapped_value, + segmented_lut_data, + color='red' + ) + + assert len(lut.RedPaletteColorLookupTableDescriptor) == 3 + assert lut.RedPaletteColorLookupTableDescriptor[0] == len(lut_data) + assert lut.RedPaletteColorLookupTableDescriptor[1] == 32 + assert lut.RedPaletteColorLookupTableDescriptor[2] == 16 + assert not hasattr(lut, 'BluePaletteColorLookupTableDescriptor') + assert not hasattr(lut, 'GreenPaletteColorLookupTableDescriptor') + assert len(lut.SegmentedRedPaletteColorLookupTableData) == ( + segmented_lut_data.shape[0] * 2 + ) + assert not hasattr(lut, 'SegmentedBluePaletteColorLookupTableData') + assert not hasattr(lut, 'SegmentedGreenPaletteColorLookupTableData') + + assert lut.number_of_entries == lut_data.shape[0] + assert lut.first_mapped_value == first_mapped_value + assert lut.bits_per_entry == 16 + assert lut.lut_data.dtype == np.uint16 + np.array_equal(lut.segmented_lut_data, segmented_lut_data) + np.array_equal(lut.lut_data, lut_data) + + arr = np.array([32, 33, 32, 38, 41]) + expected = np.array([4, 5, 4, 10, 30]) + output = lut.apply(arr) + assert output.dtype == np.uint16 + assert np.array_equal(output, expected) + + for dtype in [ + np.uint16, + np.uint32, + np.float32, + np.float64, + np.int32, + np.int64, + ]: + output = lut.apply(arr, dtype=dtype) + assert output.dtype == dtype + assert np.array_equal(output, expected.astype(dtype)) + + for dtype in [ + np.uint8, + np.int8, + np.int16, + ]: + with pytest.raises(TypeError): + lut.apply(arr, dtype=dtype) + + def test_construction_8bit(self): + segmented_lut_data = np.array( + [ + 0, 3, 4, 5, 6, # literal [4, 5, 6] + 1, 3, 0, # ramp down to zero in 3 steps [4, 2, 0] + 0, 2, 10, 20, # literal [10, 20] + 1, 4, 40, # ramp up to 40 in 4 steps [25, 30, 35, 40] + ], + dtype=np.uint8 + ) + + # The expected expansion of the above + lut_data = np.array( + [4, 5, 6, 4, 2, 0, 10, 20, 25, 30, 35, 40], + dtype=np.uint8, + ) + first_mapped_value = 0 + lut = SegmentedPaletteColorLUT( + first_mapped_value, + segmented_lut_data, + color='blue', + ) + + assert len(lut.BluePaletteColorLookupTableDescriptor) == 3 + assert lut.BluePaletteColorLookupTableDescriptor[0] == len(lut_data) + assert lut.BluePaletteColorLookupTableDescriptor[1] == 0 + assert lut.BluePaletteColorLookupTableDescriptor[2] == 8 + assert not hasattr(lut, 'RedPaletteColorLookupTableDescriptor') + assert not hasattr(lut, 'GreenPaletteColorLookupTableDescriptor') + expected_len = segmented_lut_data.shape[0] + assert len(lut.SegmentedBluePaletteColorLookupTableData) == expected_len + assert not hasattr(lut, 'SegmentedRedPaletteColorLookupTableData') + assert not hasattr(lut, 'SegmentedGreenPaletteColorLookupTableData') + + assert lut.number_of_entries == lut_data.shape[0] + assert lut.first_mapped_value == first_mapped_value + assert lut.bits_per_entry == 8 + assert lut.lut_data.dtype == np.uint8 + np.array_equal(lut.lut_data, lut_data) + + arr = np.array([0, 1, 0, 6, 9]) + expected = np.array([4, 5, 4, 10, 30]) + output = lut.apply(arr) + assert output.dtype == np.uint8 + assert np.array_equal(output, expected) + + for dtype in [ + np.uint16, + np.uint32, + np.int16, + np.float32, + np.float64, + np.int32, + np.int64, + ]: + output = lut.apply(arr, dtype=dtype) + assert output.dtype == dtype + assert np.array_equal(output, expected.astype(dtype)) + + for dtype in [ + np.int8, + ]: + with pytest.raises(TypeError): + lut.apply(arr, dtype=dtype) + + def test_construction_invalid_opcode(self): + # Example with an invalid opcode (4) + segmented_lut_data = np.array([4, 0, 0], dtype=np.uint8) + + msg = "Encountered unexpected segment type 4" + with pytest.raises(ValueError, match=msg): + SegmentedPaletteColorLUT( + 0, + segmented_lut_data, + 'red', + ) + + def test_construction_linear_segment_first(self): + # Linear segment (opcode 1) may not be the first segment + segmented_lut_data = np.array([1, 10, 10], dtype=np.uint8) + + msg = ( + "Error reading segmented LUT data, a linear segment may not be " + "used as the first segment." + ) + with pytest.raises(ValueError, match=msg): + SegmentedPaletteColorLUT( + 0, + segmented_lut_data, + 'red', + ) + + def test_extract_from_dataset(self): + for dtype in [np.uint8, np.uint16]: + for color in ['red', 'green', 'blue']: + segmented_lut_data = np.array( + [ + 0, 3, 4, 5, 6, # literal [4, 5, 6] + 1, 3, 0, # ramp down to zero in 3 steps [4, 2, 0] + 0, 2, 10, 20, # literal [10, 20] + 1, 4, 40, # ramp up to 40 in 4 steps [25, 30, 35, 40] + ], + dtype=np.uint8 + ) + # the expected expansion of the above + lut_data = np.array( + [4, 5, 6, 4, 2, 0, 10, 20, 25, 30, 35, 40], + dtype=np.uint8, + ) + first_mapped_value = 0 + lut = SegmentedPaletteColorLUT( + first_mapped_value, + segmented_lut_data, + color=color + ) + + # Create a "plain" pydicom dataset containing the same + # attributes + ds = Dataset() + + for k, v in lut.items(): + ds[k] = v + + extracted = SegmentedPaletteColorLUT.extract_from_dataset( + ds, + color=color, + ) + assert extracted == lut + assert np.array_equal(lut.lut_data, lut_data) + class TestPaletteColorLUTTransformation(TestCase): @@ -2383,6 +2625,51 @@ def test_construction_from_combined(self): assert np.array_equal(lut.blue_lut.lut_data, b_lut_data) assert np.array_equal(lut.green_lut.lut_data, g_lut_data) + def test_extract_from_dataset(self): + for bits, dtype in [(8, np.uint8), (16, np.uint16)]: + r_lut_data = np.arange(10, 120, dtype=dtype) + g_lut_data = np.arange(20, 130, dtype=dtype) + b_lut_data = np.arange(30, 140, dtype=dtype) + first_mapped_value = 32 + lut_uid = UID() + r_lut = PaletteColorLUT( + first_mapped_value, + r_lut_data, + color='red', + ) + g_lut = PaletteColorLUT( + first_mapped_value, + g_lut_data, + color='green', + ) + b_lut = PaletteColorLUT( + first_mapped_value, + b_lut_data, + color='blue', + ) + combined_lut_data = np.stack( + [r_lut_data, g_lut_data, b_lut_data] + ).T + instance = PaletteColorLUTTransformation( + red_lut=r_lut, + green_lut=g_lut, + blue_lut=b_lut, + palette_color_lut_uid=lut_uid, + ) + + # Create a "plain" pydicom dataset containing the same attributes + ds = Dataset() + + for k, v in instance.items(): + ds[k] = v + + extracted = PaletteColorLUTTransformation.extract_from_dataset(ds) + assert extracted == instance + assert np.array_equal( + instance.combined_lut_data, + combined_lut_data, + ) + class TestSpecimenDescription(TestCase): def test_construction(self): diff --git a/tests/test_legacy.py b/tests/test_legacy.py index c8126605c..348d19ee8 100644 --- a/tests/test_legacy.py +++ b/tests/test_legacy.py @@ -673,7 +673,8 @@ def test_inconsistent_type_2_attribute( assert getattr(converted, keyword) is None -def test_optional_module(modality: Modality) -> None: +@pytest.mark.parametrize('strict', [False, True]) +def test_optional_module(modality: Modality, strict: bool) -> None: """Check that presence of the required attributes triggers inclusion of optional module. @@ -684,13 +685,14 @@ def test_optional_module(modality: Modality) -> None: modality, 1, True, True ) - # Including just one of the two required attributes should cause the entire - # module to be omitted + # In strict mode, including just one of the two required attributes should + # cause the entire module to be omitted for ds in legacy_datasets: ds.ClinicalTrialSponsorName = 'Sponsor' # type 1 ds.ClinicalTrialProtocolName = 'Protocol Name' # type 2 ds.ClinicalTrialSiteName = 'Site Name' # type 2 ds.IssuerOfClinicalTrialSubjectID = "Issuer" # type 3 + # 'ClinicalTrialProtocolID' is omitted converted = LegacyConvertedClass( legacy_datasets, @@ -698,12 +700,21 @@ def test_optional_module(modality: Modality) -> None: series_number=1, sop_instance_uid=UID(), instance_number=1, + strict=strict, ) - assert 'ClinicalTrialSponsorName' not in converted - assert 'ClinicalTrialProtocolID' not in converted - assert 'ClinicalTrialProtocolName' not in converted - assert 'IssuerOfClinicalTrialSubjectID' not in converted + if strict: + assert 'ClinicalTrialSponsorName' not in converted + assert 'ClinicalTrialProtocolID' not in converted + assert 'ClinicalTrialProtocolName' not in converted + assert 'ClinicalTrialSiteName' not in converted + assert 'IssuerOfClinicalTrialSubjectID' not in converted + else: + assert 'ClinicalTrialProtocolID' not in converted # missing + assert 'ClinicalTrialSponsorName' in converted + assert 'ClinicalTrialProtocolName' in converted + assert 'ClinicalTrialSiteName' in converted + assert 'IssuerOfClinicalTrialSubjectID' in converted # Now additionally including the missing required attribute should trigger # the whole module to be included @@ -716,6 +727,7 @@ def test_optional_module(modality: Modality) -> None: series_number=1, sop_instance_uid=UID(), instance_number=1, + strict=strict, ) assert converted.ClinicalTrialSponsorName == 'Sponsor' @@ -2109,6 +2121,80 @@ def test_transcode_custom_workers(): assert np.array_equal(converted.pixel_array, expected_pixels) +def test_enhanced_functional_groups(): + """Test functional groups from enhanced IODs.""" + # Some test files that have a lot of attributes that can be placed into the + # enhanced CT functional groups + ct_files = [ + get_testdata_file('dicomdirtests/77654033/CT2/17136', read=True), + get_testdata_file('dicomdirtests/77654033/CT2/17196', read=True), + get_testdata_file('dicomdirtests/77654033/CT2/17166', read=True), + ] + + converted = LegacyConvertedEnhancedCTImage( + ct_files, + series_instance_uid=UID(), + series_number=1, + sop_instance_uid=UID(), + instance_number=1, + ) + + sfgs = ( + converted + .SharedFunctionalGroupsSequence[0] + ) + unassigned_shared_seq = ( + sfgs + .UnassignedSharedConvertedAttributesSequence[0] + ) + + expected_attributes = [ + ('CTAcquisitionDetailsSequence', 'DataCollectionDiameter'), + ('CTAcquisitionDetailsSequence', 'TableHeight'), + ('CTGeometrySequence', 'DistanceSourceToDetector'), + ('CTReconstructionSequence', 'ConvolutionKernel'), + ('CTXRayDetailsSequence', 'KVP'), + ] + + for seq_kw, attr_kw in expected_attributes: + # Check the enhanced group is present and the element is not placed in + # the unassigned groups + seq = getattr(sfgs, seq_kw)[0] + val = getattr(seq, attr_kw) + orig_val = getattr(ct_files[0], attr_kw) + assert val == orig_val + + assert not hasattr(unassigned_shared_seq, seq_kw) + + # Now try without the enhanced functional IOD + converted = LegacyConvertedEnhancedCTImage( + ct_files, + series_instance_uid=UID(), + series_number=1, + sop_instance_uid=UID(), + instance_number=1, + include_enhanced_groups=False, + ) + + sfgs = ( + converted + .SharedFunctionalGroupsSequence[0] + ) + unassigned_shared_seq = ( + sfgs + .UnassignedSharedConvertedAttributesSequence[0] + ) + + for seq_kw, attr_kw in expected_attributes: + # Check the enhanced group is not present so the element is placed in + # the unassigned groups + assert not hasattr(sfgs, seq_kw) + + val = getattr(unassigned_shared_seq, attr_kw) + orig_val = getattr(ct_files[0], attr_kw) + assert val == orig_val + + def test_from_dataset(modality: Modality) -> None: LegacyConvertedClass = MODALITY_CLASS_MAP[modality] data_generator = DicomGenerator(5) diff --git a/tests/test_sc.py b/tests/test_sc.py index 0d3148896..3074f2ddb 100644 --- a/tests/test_sc.py +++ b/tests/test_sc.py @@ -1,6 +1,5 @@ from pathlib import Path from io import BytesIO -import unittest import numpy as np import pytest @@ -14,175 +13,215 @@ JPEGLSLossless, JPEGLSNearLossless, ) -from pydicom.valuerep import DA, TM from highdicom import IssuerOfIdentifier, SpecimenDescription from highdicom.sc import SCImage from highdicom import UID from highdicom.frame import decode_frame +from .utils import write_and_read_dataset -class TestSCImage(unittest.TestCase): - - def setUp(self): - super().setUp() - self._rgb_pixel_array = np.zeros((10, 10, 3), dtype=np.uint8) - self._monochrome_pixel_array = np.zeros((10, 10), dtype=np.uint16) - self._study_instance_uid = UID() - self._series_instance_uid = UID() - self._sop_instance_uid = UID() - self._series_number = int(np.random.choice(100)) + 1 - self._instance_number = int(np.random.choice(100)) + 1 - self._manufacturer = 'ABC' - self._laterality = 'L' - self._pixel_spacing = [0.5, 0.5] - self._patient_orientation = ['A', 'R'] - self._container_identifier = str(np.random.choice(100)) - self._specimen_identifier = str(np.random.choice(100)) - self._specimen_uid = UID() - file_path = Path(__file__) - data_dir = file_path.parent.parent.joinpath('data') - self._ref_dataset = dcmread( - str(data_dir.joinpath('test_files', 'ct_image.dcm')) + +def generate_frame( + shape: tuple[int, ...], + dtype: type, + pixel_representation: int, + bits_stored: int, +): + rng = np.random.default_rng(0) + if pixel_representation == 1: + low = -(2 ** (bits_stored - 1)) + high = 2 ** (bits_stored - 1) + else: + low = 0 + high = 2 ** bits_stored - 1 + + frame = rng.integers( + low, high, shape, dtype=dtype, + ) + # ensure the extremes are exercised + frame[0, 0] = low + frame[0, 1] = high - 1 + + return frame + + +def get_array_after_writing(instance): + # Write DICOM object to buffer, read it again and reconstruct the mask + with BytesIO() as fp: + instance.save_as(fp) + fp.seek(0) + ds = dcmread(fp) + + decoded_frame_arrays = [ + decode_frame( + value, + transfer_syntax_uid=ds.file_meta.TransferSyntaxUID, + rows=ds.Rows, + columns=ds.Columns, + samples_per_pixel=ds.SamplesPerPixel, + bits_allocated=ds.BitsAllocated, + bits_stored=ds.BitsStored, + photometric_interpretation=ds.PhotometricInterpretation, + pixel_representation=ds.PixelRepresentation, + planar_configuration=getattr(ds, 'PlanarConfiguration', None) ) + for (value, ) in generate_fragmented_frames(instance.PixelData) + ] + if len(decoded_frame_arrays) > 1: + return np.stack(decoded_frame_arrays) + return decoded_frame_arrays[0] - @staticmethod - def get_array_after_writing(instance): - # Write DICOM object to buffer, read it again and reconstruct the mask - with BytesIO() as fp: - instance.save_as(fp) - fp.seek(0) - ds = dcmread(fp) - - decoded_frame_arrays = [ - decode_frame( - value, - transfer_syntax_uid=ds.file_meta.TransferSyntaxUID, - rows=ds.Rows, - columns=ds.Columns, - samples_per_pixel=ds.SamplesPerPixel, - bits_allocated=ds.BitsAllocated, - bits_stored=ds.BitsStored, - photometric_interpretation=ds.PhotometricInterpretation, - pixel_representation=ds.PixelRepresentation, - planar_configuration=getattr(ds, 'PlanarConfiguration', None) - ) - for (value, ) in generate_fragmented_frames(instance.PixelData) - ] - if len(decoded_frame_arrays) > 1: - return np.stack(decoded_frame_arrays) - return decoded_frame_arrays[0] - def test_construct_rgb_patient(self): - bits_allocated = 8 +def test_construct_rgb_patient(): + study_uid = UID() + series_uid = UID() + sop_uid = UID() + photometric_interpretation = 'RGB' + coordinate_system = 'PATIENT' + frame = generate_frame( + (10, 10, 3), np.uint8, 0, 8 + ) + instance = SCImage( + pixel_array=frame, + photometric_interpretation=photometric_interpretation, + coordinate_system=coordinate_system, + study_instance_uid=study_uid, + series_instance_uid=series_uid, + sop_instance_uid=sop_uid, + series_number=34, + instance_number=7, + manufacturer='ABC', + patient_orientation=('A', 'R'), + laterality='L', + pixel_spacing=(0.5, 0.5), + ) + assert instance.BitsAllocated == 8 + assert instance.BitsStored == 8 + assert instance.SamplesPerPixel == 3 + assert instance.PlanarConfiguration == 0 + assert instance.PhotometricInterpretation == photometric_interpretation + assert instance.StudyInstanceUID == study_uid + assert instance.SeriesInstanceUID == series_uid + assert instance.SOPInstanceUID == sop_uid + assert instance.SeriesNumber == 34 + assert instance.InstanceNumber == 7 + assert instance.Manufacturer == 'ABC' + assert instance.Laterality == 'L' + assert instance.PatientOrientation == ['A', 'R'] + assert instance.AccessionNumber is None + assert instance.PatientName is None + assert instance.PatientSex is None + assert instance.StudyTime is None + assert instance.StudyTime is None + assert instance.PixelSpacing == [0.5, 0.5] + assert instance.PixelData == frame.tobytes() + with pytest.raises(AttributeError): + instance.ContainerIdentifier # noqa: B018 + instance.SpecimenDescriptionSequence # noqa: B018 + instance.ContainerTypeCodeSequence # noqa: B018 + instance.IssuerOfTheContainerIdentifierSequence # noqa: B018 + + +def test_construct_rgb_patient_missing_parameter(): + frame = generate_frame( + (10, 10, 3), np.uint8, 0, 8 + ) + with pytest.raises(TypeError): photometric_interpretation = 'RGB' coordinate_system = 'PATIENT' - instance = SCImage( - pixel_array=self._rgb_pixel_array, + SCImage( + pixel_array=frame, photometric_interpretation=photometric_interpretation, - bits_allocated=bits_allocated, coordinate_system=coordinate_system, - study_instance_uid=self._study_instance_uid, - series_instance_uid=self._series_instance_uid, - sop_instance_uid=self._sop_instance_uid, - series_number=self._series_number, - instance_number=self._instance_number, - manufacturer=self._manufacturer, - patient_orientation=self._patient_orientation, - laterality=self._laterality, - pixel_spacing=self._pixel_spacing, + study_instance_uid=UID(), + series_instance_uid=UID(), + sop_instance_uid=UID(), + series_number=34, + instance_number=7, + manufacturer='ABC', ) - assert instance.BitsAllocated == bits_allocated - assert instance.SamplesPerPixel == 3 - assert instance.PlanarConfiguration == 0 - assert instance.PhotometricInterpretation == photometric_interpretation - assert instance.StudyInstanceUID == self._study_instance_uid - assert instance.SeriesInstanceUID == self._series_instance_uid - assert instance.SOPInstanceUID == self._sop_instance_uid - assert instance.SeriesNumber == self._series_number - assert instance.InstanceNumber == self._instance_number - assert instance.Manufacturer == self._manufacturer - assert instance.Laterality == self._laterality - assert instance.PatientOrientation == self._patient_orientation - assert instance.AccessionNumber is None - assert instance.PatientName is None - assert instance.PatientSex is None - assert instance.StudyTime is None - assert instance.StudyTime is None - assert instance.PixelSpacing == [0.5, 0.5] - assert instance.PixelData == self._rgb_pixel_array.tobytes() - with pytest.raises(AttributeError): - instance.ContainerIdentifier # noqa: B018 - instance.SpecimenDescriptionSequence # noqa: B018 - instance.ContainerTypeCodeSequence # noqa: B018 - instance.IssuerOfTheContainerIdentifierSequence # noqa: B018 - - def test_construct_rgb_patient_missing_parameter(self): - with pytest.raises(TypeError): - bits_allocated = 8 - photometric_interpretation = 'RGB' - coordinate_system = 'PATIENT' - SCImage( - pixel_array=self._rgb_pixel_array, - photometric_interpretation=photometric_interpretation, - bits_allocated=bits_allocated, - coordinate_system=coordinate_system, - study_instance_uid=self._study_instance_uid, - series_instance_uid=self._series_instance_uid, - sop_instance_uid=self._sop_instance_uid, - series_number=self._series_number, - instance_number=self._instance_number, - manufacturer=self._manufacturer, - ) - def test_construct_rgb_slide_single_specimen(self): - bits_allocated = 8 - photometric_interpretation = 'RGB' - coordinate_system = 'SLIDE' - specimen_description = SpecimenDescription( - specimen_id=self._specimen_identifier, - specimen_uid=self._specimen_uid - ) - instance = SCImage( - pixel_array=self._rgb_pixel_array, + +def test_construct_rgb_slide_single_specimen(): + photometric_interpretation = 'RGB' + coordinate_system = 'SLIDE' + study_uid = UID() + series_uid = UID() + sop_uid = UID() + specimen_uid = UID() + specimen_description = SpecimenDescription( + specimen_id='specimen id', + specimen_uid=specimen_uid, + ) + frame = generate_frame( + (10, 10, 3), np.uint8, 0, 8 + ) + instance = SCImage( + pixel_array=frame, + photometric_interpretation=photometric_interpretation, + coordinate_system=coordinate_system, + study_instance_uid=study_uid, + series_instance_uid=series_uid, + sop_instance_uid=sop_uid, + series_number=34, + instance_number=7, + manufacturer='ABC', + container_identifier='container id', + specimen_descriptions=[specimen_description] + ) + assert instance.BitsAllocated == 8 + assert instance.BitsStored == 8 + assert instance.SamplesPerPixel == 3 + assert instance.PlanarConfiguration == 0 + assert instance.PhotometricInterpretation == photometric_interpretation + assert instance.StudyInstanceUID == study_uid + assert instance.SeriesInstanceUID == series_uid + assert instance.SOPInstanceUID == sop_uid + assert instance.SeriesNumber == 34 + assert instance.InstanceNumber == 7 + assert instance.Manufacturer == 'ABC' + assert instance.ContainerIdentifier == 'container id' + assert len(instance.ContainerTypeCodeSequence) == 1 + assert len(instance.IssuerOfTheContainerIdentifierSequence) == 0 + assert len(instance.SpecimenDescriptionSequence) == 1 + specimen_item = instance.SpecimenDescriptionSequence[0] + assert specimen_item.SpecimenIdentifier == 'specimen id' + assert specimen_item.SpecimenUID == specimen_uid + assert instance.AccessionNumber is None + assert instance.PatientName is None + assert instance.PatientSex is None + assert instance.StudyTime is None + assert instance.StudyTime is None + assert instance.PixelData == frame.tobytes() + with pytest.raises(AttributeError): + instance.Laterality # noqa: B018 + instance.PatientOrientation # noqa: B018 + + +def test_construct_rgb_slide_single_specimen_missing_parameter(): + photometric_interpretation = 'RGB' + coordinate_system = 'SLIDE' + specimen_description = SpecimenDescription( + specimen_id='specimen id', + specimen_uid=UID() + ) + frame = generate_frame( + (10, 10, 3), np.uint8, 0, 8 + ) + with pytest.raises(TypeError): + SCImage( + pixel_array=frame, photometric_interpretation=photometric_interpretation, - bits_allocated=bits_allocated, coordinate_system=coordinate_system, - study_instance_uid=self._study_instance_uid, - series_instance_uid=self._series_instance_uid, - sop_instance_uid=self._sop_instance_uid, - series_number=self._series_number, - instance_number=self._instance_number, - manufacturer=self._manufacturer, - container_identifier=self._container_identifier, + study_instance_uid=UID(), + series_instance_uid=UID(), + sop_instance_uid=UID(), + series_number=34, + instance_number=7, + manufacturer='ABC', specimen_descriptions=[specimen_description] ) - assert instance.BitsAllocated == bits_allocated - assert instance.SamplesPerPixel == 3 - assert instance.PlanarConfiguration == 0 - assert instance.PhotometricInterpretation == photometric_interpretation - assert instance.StudyInstanceUID == self._study_instance_uid - assert instance.SeriesInstanceUID == self._series_instance_uid - assert instance.SOPInstanceUID == self._sop_instance_uid - assert instance.SeriesNumber == self._series_number - assert instance.InstanceNumber == self._instance_number - assert instance.Manufacturer == self._manufacturer - assert instance.ContainerIdentifier == self._container_identifier - assert len(instance.ContainerTypeCodeSequence) == 1 - assert len(instance.IssuerOfTheContainerIdentifierSequence) == 0 - assert len(instance.SpecimenDescriptionSequence) == 1 - specimen_item = instance.SpecimenDescriptionSequence[0] - assert specimen_item.SpecimenIdentifier == self._specimen_identifier - assert specimen_item.SpecimenUID == self._specimen_uid - assert instance.AccessionNumber is None - assert instance.PatientName is None - assert instance.PatientSex is None - assert instance.StudyTime is None - assert instance.StudyTime is None - assert instance.PixelData == self._rgb_pixel_array.tobytes() - with pytest.raises(AttributeError): - instance.Laterality # noqa: B018 - instance.PatientOrientation # noqa: B018 def test_construct_rgb_slide_with_issuer_of_container_identifier(self): issuer = IssuerOfIdentifier('ISSUER') @@ -232,380 +271,976 @@ def test_construct_rgb_slide_single_specimen_missing_parameter(self): specimen_descriptions=[specimen_description] ) - def test_construct_rgb_slide_single_specimen_missing_parameter_1(self): - bits_allocated = 8 - photometric_interpretation = 'RGB' - coordinate_system = 'SLIDE' - with pytest.raises(TypeError): - SCImage( - pixel_array=self._rgb_pixel_array, - photometric_interpretation=photometric_interpretation, - bits_allocated=bits_allocated, - coordinate_system=coordinate_system, - study_instance_uid=self._study_instance_uid, - series_instance_uid=self._series_instance_uid, - sop_instance_uid=self._sop_instance_uid, - series_number=self._series_number, - instance_number=self._instance_number, - manufacturer=self._manufacturer, - container_identifier=self._container_identifier, - ) - def test_construct_monochrome_patient(self): - bits_allocated = 16 - photometric_interpretation = 'MONOCHROME2' - coordinate_system = 'PATIENT' - instance = SCImage( - pixel_array=self._monochrome_pixel_array, - photometric_interpretation=photometric_interpretation, - bits_allocated=bits_allocated, - coordinate_system=coordinate_system, - study_instance_uid=self._study_instance_uid, - series_instance_uid=self._series_instance_uid, - sop_instance_uid=self._sop_instance_uid, - series_number=self._series_number, - instance_number=self._instance_number, - manufacturer=self._manufacturer, - patient_orientation=self._patient_orientation - ) - assert instance.BitsAllocated == bits_allocated - assert instance.SamplesPerPixel == 1 - assert instance.PhotometricInterpretation == photometric_interpretation - assert instance.StudyInstanceUID == self._study_instance_uid - assert instance.SeriesInstanceUID == self._series_instance_uid - assert instance.SOPInstanceUID == self._sop_instance_uid - assert instance.SeriesNumber == self._series_number - assert instance.InstanceNumber == self._instance_number - assert instance.Manufacturer == self._manufacturer - assert instance.PatientOrientation == self._patient_orientation - assert instance.AccessionNumber is None - assert instance.PatientName is None - assert instance.PatientSex is None - assert instance.StudyTime is None - assert instance.StudyDate is None - assert instance.PixelData == self._monochrome_pixel_array.tobytes() - with pytest.raises(AttributeError): - instance.ContainerIdentifier # noqa: B018 - instance.SpecimenDescriptionSequence # noqa: B018 - instance.ContainerTypeCodeSequence # noqa: B018 - instance.IssuerOfTheContainerIdentifierSequence # noqa: B018 - - def test_monochrome_rle(self): - bits_allocated = 8 # RLE requires multiple of 8 bits - photometric_interpretation = 'MONOCHROME2' - coordinate_system = 'PATIENT' - frame = np.random.randint(0, 256, size=(256, 256), dtype=np.uint8) - instance = SCImage( +def test_construct_rgb_slide_single_specimen_missing_parameter_1(): + photometric_interpretation = 'RGB' + coordinate_system = 'SLIDE' + frame = generate_frame( + (10, 10, 3), np.uint8, 0, 8 + ) + with pytest.raises(TypeError): + SCImage( pixel_array=frame, photometric_interpretation=photometric_interpretation, - bits_allocated=bits_allocated, coordinate_system=coordinate_system, - study_instance_uid=self._study_instance_uid, - series_instance_uid=self._series_instance_uid, - sop_instance_uid=self._sop_instance_uid, - series_number=self._series_number, - instance_number=self._instance_number, - manufacturer=self._manufacturer, - patient_orientation=self._patient_orientation, - transfer_syntax_uid=RLELossless + study_instance_uid=UID(), + series_instance_uid=UID(), + sop_instance_uid=UID(), + series_number=34, + instance_number=7, + manufacturer='ABC', + container_identifier='container id', ) - assert instance.file_meta.TransferSyntaxUID == RLELossless - assert np.array_equal( - self.get_array_after_writing(instance), - frame - ) +def test_construct_monochrome_patient(): + study_uid = UID() + series_uid = UID() + sop_uid = UID() + photometric_interpretation = 'MONOCHROME2' + coordinate_system = 'PATIENT' + frame = generate_frame( + (10, 10), np.uint16, 0, 16 + ) + instance = SCImage( + pixel_array=frame, + photometric_interpretation=photometric_interpretation, + coordinate_system=coordinate_system, + study_instance_uid=study_uid, + series_instance_uid=series_uid, + sop_instance_uid=sop_uid, + series_number=34, + instance_number=7, + manufacturer='ABC', + patient_orientation=('A', 'R') + ) + assert instance.BitsAllocated == 16 + assert instance.BitsStored == 16 + assert instance.SamplesPerPixel == 1 + assert instance.PhotometricInterpretation == photometric_interpretation + assert instance.StudyInstanceUID == study_uid + assert instance.SeriesInstanceUID == series_uid + assert instance.SOPInstanceUID == sop_uid + assert instance.SeriesNumber == 34 + assert instance.InstanceNumber == 7 + assert instance.Manufacturer == 'ABC' + assert instance.PatientOrientation == ['A', 'R'] + assert instance.AccessionNumber is None + assert instance.PatientName is None + assert instance.PatientSex is None + assert instance.StudyTime is None + assert instance.StudyDate is None + assert instance.PixelData == frame.tobytes() + with pytest.raises(AttributeError): + instance.ContainerIdentifier # noqa: B018 + with pytest.raises(AttributeError): + instance.SpecimenDescriptionSequence # noqa: B018 + with pytest.raises(AttributeError): + instance.ContainerTypeCodeSequence # noqa: B018 + with pytest.raises(AttributeError): + instance.IssuerOfTheContainerIdentifierSequence # noqa: B018 - def test_rgb_rle(self): - bits_allocated = 8 # RLE requires multiple of 8 bits - photometric_interpretation = 'RGB' - coordinate_system = 'PATIENT' - frame = np.random.randint(0, 256, size=(256, 256, 3), dtype=np.uint8) - instance = SCImage( - pixel_array=frame, - photometric_interpretation=photometric_interpretation, - bits_allocated=bits_allocated, - coordinate_system=coordinate_system, - study_instance_uid=self._study_instance_uid, - series_instance_uid=self._series_instance_uid, - sop_instance_uid=self._sop_instance_uid, - series_number=self._series_number, - instance_number=self._instance_number, - manufacturer=self._manufacturer, - patient_orientation=self._patient_orientation, - transfer_syntax_uid=RLELossless - ) - assert instance.file_meta.TransferSyntaxUID == RLELossless +def test_monochrome_rle(): + photometric_interpretation = 'MONOCHROME2' + coordinate_system = 'PATIENT' + frame = generate_frame( + (12, 12), np.uint8, 0, 8 + ) + instance = SCImage( + pixel_array=frame, + photometric_interpretation=photometric_interpretation, + coordinate_system=coordinate_system, + study_instance_uid=UID(), + series_instance_uid=UID(), + sop_instance_uid=UID(), + series_number=34, + instance_number=7, + manufacturer='ABC', + patient_orientation=('A', 'R'), + transfer_syntax_uid=RLELossless + ) - assert np.array_equal( - self.get_array_after_writing(instance), - frame - ) + assert instance.file_meta.TransferSyntaxUID == RLELossless - def test_monochrome_jpeg_baseline(self): - pytest.importorskip("libjpeg") - bits_allocated = 8 - photometric_interpretation = 'MONOCHROME2' - coordinate_system = 'PATIENT' - frame = np.zeros((256, 256), dtype=np.uint8) - frame[25:55, 25:55] = 255 - instance = SCImage( + assert np.array_equal( + get_array_after_writing(instance), + frame + ) + + +def test_rgb_rle(): + photometric_interpretation = 'RGB' + coordinate_system = 'PATIENT' + frame = generate_frame( + (12, 12, 3), np.uint8, 0, 8 + ) + instance = SCImage( + pixel_array=frame, + photometric_interpretation=photometric_interpretation, + coordinate_system=coordinate_system, + study_instance_uid=UID(), + series_instance_uid=UID(), + sop_instance_uid=UID(), + series_number=34, + instance_number=7, + manufacturer='ABC', + patient_orientation=('A', 'R'), + transfer_syntax_uid=RLELossless + ) + + assert instance.file_meta.TransferSyntaxUID == RLELossless + + assert np.array_equal( + get_array_after_writing(instance), + frame + ) + + +def test_monochrome_jpeg_baseline(): + pytest.importorskip("libjpeg") + photometric_interpretation = 'MONOCHROME2' + coordinate_system = 'PATIENT' + frame = generate_frame( + (12, 12), np.uint8, 0, 8 + ) + instance = SCImage( + pixel_array=frame, + photometric_interpretation=photometric_interpretation, + coordinate_system=coordinate_system, + study_instance_uid=UID(), + series_instance_uid=UID(), + sop_instance_uid=UID(), + series_number=34, + instance_number=7, + manufacturer='ABC', + patient_orientation=('A', 'R'), + transfer_syntax_uid=JPEGBaseline8Bit + ) + + assert instance.file_meta.TransferSyntaxUID == JPEGBaseline8Bit + + assert np.allclose( + get_array_after_writing(instance), + frame, + atol=10 # tolerance for lossy compression + ) + + +def test_rgb_jpeg_baseline(): + pytest.importorskip("libjpeg") + photometric_interpretation = 'YBR_FULL_422' + coordinate_system = 'PATIENT' + frame = generate_frame( + (12, 12, 3), np.uint8, 0, 8 + ) + instance = SCImage( + pixel_array=frame, + photometric_interpretation=photometric_interpretation, + coordinate_system=coordinate_system, + study_instance_uid=UID(), + series_instance_uid=UID(), + sop_instance_uid=UID(), + series_number=34, + instance_number=7, + manufacturer='ABC', + patient_orientation=('A', 'R'), + transfer_syntax_uid=JPEGBaseline8Bit + ) + + assert instance.file_meta.TransferSyntaxUID == JPEGBaseline8Bit + + +def test_monochrome_jpeg2000lossless(): + pytest.importorskip("openjpeg") + photometric_interpretation = 'MONOCHROME2' + coordinate_system = 'PATIENT' + frame = generate_frame( + (32, 32), np.uint8, 0, 8 + ) + instance = SCImage( + pixel_array=frame, + photometric_interpretation=photometric_interpretation, + coordinate_system=coordinate_system, + study_instance_uid=UID(), + series_instance_uid=UID(), + sop_instance_uid=UID(), + series_number=34, + instance_number=7, + manufacturer='ABC', + patient_orientation=('A', 'R'), + transfer_syntax_uid=JPEG2000Lossless + ) + + assert instance.file_meta.TransferSyntaxUID == JPEG2000Lossless + + assert np.array_equal( + get_array_after_writing(instance), + frame + ) + + +def test_monochrome_jpeg2000(): + pytest.importorskip("openjpeg") + photometric_interpretation = 'MONOCHROME2' + coordinate_system = 'PATIENT' + frame = generate_frame( + (32, 32), np.uint8, 0, 8 + ) + instance = SCImage( + pixel_array=frame, + photometric_interpretation=photometric_interpretation, + coordinate_system=coordinate_system, + study_instance_uid=UID(), + series_instance_uid=UID(), + sop_instance_uid=UID(), + series_number=34, + instance_number=7, + manufacturer='ABC', + patient_orientation=('A', 'R'), + transfer_syntax_uid=JPEG2000 + ) + + assert instance.file_meta.TransferSyntaxUID == JPEG2000 + + assert np.allclose( + get_array_after_writing(instance), + frame, + atol=2 + ) + + +def test_rgb_jpeg2000(): + pytest.importorskip("openjpeg") + photometric_interpretation = 'YBR_RCT' + coordinate_system = 'PATIENT' + frame = generate_frame( + (32, 32, 3), np.uint8, 0, 8 + ) + instance = SCImage( + pixel_array=frame, + photometric_interpretation=photometric_interpretation, + coordinate_system=coordinate_system, + study_instance_uid=UID(), + series_instance_uid=UID(), + sop_instance_uid=UID(), + series_number=34, + instance_number=7, + manufacturer='ABC', + patient_orientation=('A', 'R'), + transfer_syntax_uid=JPEG2000Lossless + ) + + assert instance.file_meta.TransferSyntaxUID == JPEG2000Lossless + + assert np.array_equal( + get_array_after_writing(instance), + frame + ) + + +def test_monochrome_jpegls(): + pytest.importorskip("libjpeg") + photometric_interpretation = 'MONOCHROME2' + coordinate_system = 'PATIENT' + frame = generate_frame( + (12, 12), np.uint8, 0, 8 + ) + instance = SCImage( + pixel_array=frame, + photometric_interpretation=photometric_interpretation, + coordinate_system=coordinate_system, + study_instance_uid=UID(), + series_instance_uid=UID(), + sop_instance_uid=UID(), + series_number=34, + instance_number=7, + manufacturer='ABC', + patient_orientation=('A', 'R'), + transfer_syntax_uid=JPEGLSLossless + ) + + assert instance.file_meta.TransferSyntaxUID == JPEGLSLossless + + assert np.array_equal( + get_array_after_writing(instance), + frame + ) + + +def test_monochrome_jpegls_near_lossless(): + pytest.importorskip("libjpeg") + photometric_interpretation = 'MONOCHROME2' + coordinate_system = 'PATIENT' + frame = generate_frame( + (12, 12), np.uint16, 0, 16 + ) + instance = SCImage( + pixel_array=frame, + photometric_interpretation=photometric_interpretation, + coordinate_system=coordinate_system, + study_instance_uid=UID(), + series_instance_uid=UID(), + sop_instance_uid=UID(), + series_number=34, + instance_number=7, + manufacturer='ABC', + patient_orientation=('A', 'R'), + transfer_syntax_uid=JPEGLSNearLossless + ) + + assert instance.file_meta.TransferSyntaxUID == JPEGLSNearLossless + + assert np.allclose( + get_array_after_writing(instance), + frame, + atol=2 + ) + + +def test_rgb_jpegls(): + pytest.importorskip("libjpeg") + photometric_interpretation = 'RGB' + coordinate_system = 'PATIENT' + frame = generate_frame( + (12, 12, 3), np.uint16, 0, 8 + ) + instance = SCImage( + pixel_array=frame, + photometric_interpretation=photometric_interpretation, + coordinate_system=coordinate_system, + study_instance_uid=UID(), + series_instance_uid=UID(), + sop_instance_uid=UID(), + series_number=34, + instance_number=7, + manufacturer='ABC', + patient_orientation=('A', 'R'), + transfer_syntax_uid=JPEGLSLossless + ) + + assert instance.file_meta.TransferSyntaxUID == JPEGLSLossless + + assert np.array_equal( + get_array_after_writing(instance), + frame + ) + + +def test_construct_rgb_from_ref_dataset(): + file_path = Path(__file__) + data_dir = file_path.parent.parent.joinpath('data') + series_uid = UID() + sop_uid = UID() + + ref_dataset = dcmread( + str(data_dir.joinpath('test_files', 'ct_image.dcm')) + ) + photometric_interpretation = 'RGB' + coordinate_system = 'PATIENT' + frame = generate_frame( + (12, 12, 3), np.uint8, 0, 8 + ) + instance = SCImage.from_ref_dataset( + ref_dataset=ref_dataset, + pixel_array=frame, + photometric_interpretation=photometric_interpretation, + coordinate_system=coordinate_system, + series_instance_uid=series_uid, + sop_instance_uid=sop_uid, + series_number=34, + instance_number=7, + manufacturer='ABC', + patient_orientation=('A', 'R'), + laterality='L' + ) + assert instance.BitsAllocated == 8 + assert instance.BitsStored == 8 + assert instance.SamplesPerPixel == 3 + assert instance.PlanarConfiguration == 0 + assert instance.PhotometricInterpretation == photometric_interpretation + assert instance.StudyInstanceUID == ref_dataset.StudyInstanceUID + assert instance.SeriesInstanceUID == series_uid + assert instance.SOPInstanceUID == sop_uid + assert instance.SeriesNumber == 34 + assert instance.InstanceNumber == 7 + assert instance.Manufacturer == 'ABC' + assert instance.Laterality == 'L' + assert instance.PatientOrientation == ['A', 'R'] + assert instance.AccessionNumber == ref_dataset.AccessionNumber + assert instance.PatientName == ref_dataset.PatientName + assert instance.PatientSex == ref_dataset.PatientSex + assert instance.StudyTime == ref_dataset.StudyTime + assert instance.StudyDate == ref_dataset.StudyDate + assert instance.StudyID == ref_dataset.StudyID + assert instance.PixelData == frame.tobytes() + + +@pytest.mark.parametrize( + 'dtype,pixel_representation,bits_allocated', + [ + (np.bool, 0, 1), + (np.uint8, 0, 8), + (np.uint16, 0, 16), + (np.uint32, 0, 32), + (np.int8, 1, 8), + (np.int16, 1, 16), + (np.int32, 1, 32), + ] +) +def test_valid_monochrome_datatypes( + dtype, + pixel_representation, + bits_allocated, +): + frame = generate_frame( + shape=(64, 64), + dtype=dtype, + pixel_representation=pixel_representation, + bits_stored=bits_allocated, + ) + + instance = SCImage( + pixel_array=frame, + photometric_interpretation='MONOCHROME2', + coordinate_system='PATIENT', + study_instance_uid=UID(), + series_instance_uid=UID(), + sop_instance_uid=UID(), + series_number=1, + instance_number=1, + manufacturer='Manufacturer', + patient_orientation=('A', 'R'), + ) + assert instance.BitsAllocated == bits_allocated + assert instance.BitsStored == bits_allocated + assert instance.PixelRepresentation == pixel_representation + + reread = write_and_read_dataset(instance) + read_frame = reread.pixel_array + + assert np.array_equal(read_frame, frame) + assert np.array_equal(instance.get_frame(1), frame) + + +@pytest.mark.parametrize( + 'dtype,pixel_representation,bits_allocated', + [ + (np.uint64, 0, 64), + (np.int64, 1, 64), + ] +) +def test_invalid_monochrome_datatypes( + dtype, + pixel_representation, + bits_allocated, +): + frame = generate_frame( + shape=(64, 64), + dtype=dtype, + pixel_representation=pixel_representation, + bits_stored=bits_allocated, + ) + + match = 'Pixel array has an unexpected bit depth' + with pytest.raises(TypeError, match=match): + SCImage( pixel_array=frame, - photometric_interpretation=photometric_interpretation, - bits_allocated=bits_allocated, - coordinate_system=coordinate_system, - study_instance_uid=self._study_instance_uid, - series_instance_uid=self._series_instance_uid, - sop_instance_uid=self._sop_instance_uid, - series_number=self._series_number, - instance_number=self._instance_number, - manufacturer=self._manufacturer, - patient_orientation=self._patient_orientation, - transfer_syntax_uid=JPEGBaseline8Bit + photometric_interpretation='MONOCHROME2', + coordinate_system='PATIENT', + study_instance_uid=UID(), + series_instance_uid=UID(), + sop_instance_uid=UID(), + series_number=1, + instance_number=1, + manufacturer='Manufacturer', + patient_orientation=('A', 'R'), ) - assert instance.file_meta.TransferSyntaxUID == JPEGBaseline8Bit - assert np.allclose( - self.get_array_after_writing(instance), - frame, - atol=5 # tolerance for lossy compression +@pytest.mark.parametrize( + 'dtype,pixel_representation,bits_allocated', + [ + (np.uint8, 0, 8), + (np.uint16, 0, 16), + ] +) +def test_valid_color_datatypes( + dtype, + pixel_representation, + bits_allocated, +): + frame = generate_frame( + shape=(64, 64, 3), + dtype=dtype, + pixel_representation=pixel_representation, + bits_stored=bits_allocated, + ) + instance = SCImage( + pixel_array=frame, + photometric_interpretation='RGB', + coordinate_system='PATIENT', + study_instance_uid=UID(), + series_instance_uid=UID(), + sop_instance_uid=UID(), + series_number=1, + instance_number=1, + manufacturer='Manufacturer', + patient_orientation=('A', 'R'), + ) + assert instance.BitsAllocated == bits_allocated + assert instance.BitsStored == bits_allocated + assert instance.PixelRepresentation == pixel_representation + + reread = write_and_read_dataset(instance) + read_frame = reread.pixel_array + + assert np.array_equal(read_frame, frame) + + +@pytest.mark.parametrize( + 'dtype,pixel_representation,bits_allocated', + [ + (np.bool, 0, 1), + (np.uint64, 0, 64), + (np.int8, 1, 8), + (np.int16, 1, 16), + (np.int32, 1, 32), + (np.int64, 1, 64), + ] +) +def test_invalid_color_datatypes( + dtype, + pixel_representation, + bits_allocated, +): + frame = generate_frame( + shape=(64, 64, 3), + dtype=dtype, + pixel_representation=pixel_representation, + bits_stored=bits_allocated, + ) + + if frame.dtype.kind == 'u': + match = 'Pixel array has an unexpected bit depth' + else: + match = ( + 'Pixel array must have an unsigned integer datatype for color ' + 'images' ) - def test_rgb_jpeg_baseline(self): - pytest.importorskip("libjpeg") - bits_allocated = 8 - photometric_interpretation = 'YBR_FULL_422' - coordinate_system = 'PATIENT' - frame = np.zeros((256, 256, 3), dtype=np.uint8) - frame[25:55, 25:55, 0] = 255 - frame[35:65, 35:55, 1] = 255 - instance = SCImage( + with pytest.raises(TypeError, match=match): + SCImage( pixel_array=frame, - photometric_interpretation=photometric_interpretation, - bits_allocated=bits_allocated, - coordinate_system=coordinate_system, - study_instance_uid=self._study_instance_uid, - series_instance_uid=self._series_instance_uid, - sop_instance_uid=self._sop_instance_uid, - series_number=self._series_number, - instance_number=self._instance_number, - manufacturer=self._manufacturer, - patient_orientation=self._patient_orientation, - transfer_syntax_uid=JPEGBaseline8Bit + photometric_interpretation='RGB', + coordinate_system='PATIENT', + study_instance_uid=UID(), + series_instance_uid=UID(), + sop_instance_uid=UID(), + series_number=1, + instance_number=1, + manufacturer='Manufacturer', + patient_orientation=('A', 'R'), ) - assert instance.file_meta.TransferSyntaxUID == JPEGBaseline8Bit - reread_frame = self.get_array_after_writing(instance) - np.testing.assert_allclose(frame, reread_frame, rtol=1.2) +@pytest.mark.parametrize( + 'dtype,bits_allocated,bits_stored,pixel_representation', + [ + (np.uint8, 8, 4, 0), + (np.uint16, 16, 12, 0), + (np.uint16, 16, 16, 0), + (np.int16, 16, 12, 1), + ], +) +def test_bits_stored( + bits_allocated: int, + bits_stored: int, + pixel_representation: int, + dtype: type, +): + frame = generate_frame( + shape=(64, 64), + dtype=dtype, + pixel_representation=pixel_representation, + bits_stored=bits_stored, + ) - def test_monochrome_jpeg2000lossless(self): - pytest.importorskip("openjpeg") - bits_allocated = 8 - photometric_interpretation = 'MONOCHROME2' - coordinate_system = 'PATIENT' - frame = np.random.randint(0, 256, size=(256, 256), dtype=np.uint8) - instance = SCImage( - pixel_array=frame, - photometric_interpretation=photometric_interpretation, - bits_allocated=bits_allocated, - coordinate_system=coordinate_system, - study_instance_uid=self._study_instance_uid, - series_instance_uid=self._series_instance_uid, - sop_instance_uid=self._sop_instance_uid, - series_number=self._series_number, - instance_number=self._instance_number, - manufacturer=self._manufacturer, - patient_orientation=self._patient_orientation, - transfer_syntax_uid=JPEG2000Lossless - ) + instance = SCImage( + pixel_array=frame, + photometric_interpretation='MONOCHROME2', + coordinate_system='PATIENT', + study_instance_uid=UID(), + series_instance_uid=UID(), + sop_instance_uid=UID(), + series_number=1, + instance_number=1, + manufacturer='Manufacturer', + patient_orientation=('A', 'R'), + bits_stored=bits_stored, + ) - assert instance.file_meta.TransferSyntaxUID == JPEG2000Lossless + assert instance.BitsAllocated == bits_allocated + assert instance.BitsStored == bits_stored - assert np.array_equal( - self.get_array_after_writing(instance), - frame - ) + reread = write_and_read_dataset(instance) + read_frame = reread.pixel_array - def test_monochrome_jpeg2000(self): - pytest.importorskip("openjpeg") - bits_allocated = 8 - photometric_interpretation = 'MONOCHROME2' - coordinate_system = 'PATIENT' - frame = np.random.randint(0, 256, size=(256, 256), dtype=np.uint8) - instance = SCImage( + assert np.array_equal(read_frame, frame) + + +@pytest.mark.parametrize( + 'dtype,bits_allocated,bits_stored,pixel_representation', + [ + (np.uint8, 8, 4, 0), + (np.uint16, 16, 12, 0), + (np.int16, 16, 12, 1), + ], +) +def test_invalid_bits_stored( + bits_allocated: int, + bits_stored: int, + pixel_representation: int, + dtype: type, +): + frame = generate_frame( + shape=(64, 64), + dtype=dtype, + pixel_representation=pixel_representation, + bits_stored=bits_allocated, + ) + + match = ( + "Provided 'pixel_array' cannot be represented with " + "the specified number of 'bits_stored'" + ) + with pytest.raises(ValueError, match=match): + SCImage( pixel_array=frame, - photometric_interpretation=photometric_interpretation, - bits_allocated=bits_allocated, - coordinate_system=coordinate_system, - study_instance_uid=self._study_instance_uid, - series_instance_uid=self._series_instance_uid, - sop_instance_uid=self._sop_instance_uid, - series_number=self._series_number, - instance_number=self._instance_number, - manufacturer=self._manufacturer, - patient_orientation=self._patient_orientation, - transfer_syntax_uid=JPEG2000 + photometric_interpretation='MONOCHROME2', + coordinate_system='PATIENT', + study_instance_uid=UID(), + series_instance_uid=UID(), + sop_instance_uid=UID(), + series_number=1, + instance_number=1, + manufacturer='Manufacturer', + patient_orientation=('A', 'R'), + bits_stored=bits_stored, ) - assert instance.file_meta.TransferSyntaxUID == JPEG2000 - assert np.allclose( - self.get_array_after_writing(instance), - frame, - atol=2 +def test_bits_stored_greater_than_allocated(): + match = ( + "'bits_stored' must be an integer no greater than the number of " + "bits per pixel in the input array." + ) + with pytest.raises(ValueError, match=match): + SCImage( + pixel_array=np.zeros((64, 64), dtype=np.uint8), + photometric_interpretation='MONOCHROME2', + coordinate_system='PATIENT', + study_instance_uid=UID(), + series_instance_uid=UID(), + sop_instance_uid=UID(), + series_number=1, + instance_number=1, + manufacturer='Manufacturer', + patient_orientation=('A', 'R'), + bits_stored=9, # greater than bits_allocated (8) ) - def test_rgb_jpeg2000(self): - pytest.importorskip("openjpeg") - bits_allocated = 8 - photometric_interpretation = 'YBR_RCT' - coordinate_system = 'PATIENT' - frame = np.random.randint(0, 256, size=(256, 256, 3), dtype=np.uint8) - instance = SCImage( + +def test_construct_with_spatial_info(): + study_uid = UID() + series_uid = UID() + sop_uid = UID() + frame_of_reference_uid = UID() + photometric_interpretation = 'MONOCHROME2' + coordinate_system = 'PATIENT' + frame = generate_frame( + (10, 10), np.uint16, 0, 16 + ) + image_position = [1, 2, 3] + image_orientation = [1, 0, 0, 0, 1, 0] + pixel_spacing = [0.3, 0.4] + instance = SCImage( + pixel_array=frame, + photometric_interpretation=photometric_interpretation, + coordinate_system=coordinate_system, + study_instance_uid=study_uid, + series_instance_uid=series_uid, + sop_instance_uid=sop_uid, + series_number=34, + instance_number=7, + manufacturer='ABC', + image_orientation=image_orientation, + image_position=image_position, + pixel_spacing=pixel_spacing, + frame_of_reference_uid=frame_of_reference_uid, + ) + + assert instance.ImageOrientationPatient == image_orientation + assert instance.ImagePositionPatient == image_position + assert instance.PatientOrientation == ['L', 'P'] # inferred + assert instance.PixelSpacing == pixel_spacing + assert instance.SliceThickness is None + assert 'SpacingBetweenSlices' not in instance + assert instance.FrameOfReferenceUID == frame_of_reference_uid + + +def test_construct_with_spatial_info_all(): + study_uid = UID() + series_uid = UID() + sop_uid = UID() + frame_of_reference_uid = UID() + photometric_interpretation = 'MONOCHROME2' + coordinate_system = 'PATIENT' + frame = generate_frame( + (10, 10), np.uint16, 0, 16 + ) + image_position = [1, 2, 3] + image_orientation = [1, 0, 0, 0, 1, 0] + pixel_spacing = [0.3, 0.4] + instance = SCImage( + pixel_array=frame, + photometric_interpretation=photometric_interpretation, + coordinate_system=coordinate_system, + study_instance_uid=study_uid, + series_instance_uid=series_uid, + sop_instance_uid=sop_uid, + series_number=34, + instance_number=7, + manufacturer='ABC', + image_orientation=image_orientation, + image_position=image_position, + pixel_spacing=pixel_spacing, + slice_thickness=3.4, + spacing_between_slices=1.7, + frame_of_reference_uid=frame_of_reference_uid, + ) + + assert instance.ImageOrientationPatient == image_orientation + assert instance.ImagePositionPatient == image_position + assert instance.PatientOrientation == ['L', 'P'] # inferred + assert instance.PixelSpacing == pixel_spacing + assert instance.SliceThickness == 3.4 + assert instance.SpacingBetweenSlices == 1.7 + assert instance.FrameOfReferenceUID == frame_of_reference_uid + + +def test_construct_with_spatial_info_missing_pos(): + study_uid = UID() + series_uid = UID() + sop_uid = UID() + frame_of_reference_uid = UID() + photometric_interpretation = 'MONOCHROME2' + coordinate_system = 'PATIENT' + frame = generate_frame( + (10, 10), np.uint16, 0, 16 + ) + image_orientation = [1, 0, 0, 0, 1, 0] + pixel_spacing = [0.3, 0.4] + msg = ( + "Both 'image_position' and 'image_orientation' must be " + "provided if either is provided." + ) + with pytest.raises(TypeError, match=msg): + SCImage( pixel_array=frame, photometric_interpretation=photometric_interpretation, - bits_allocated=bits_allocated, coordinate_system=coordinate_system, - study_instance_uid=self._study_instance_uid, - series_instance_uid=self._series_instance_uid, - sop_instance_uid=self._sop_instance_uid, - series_number=self._series_number, - instance_number=self._instance_number, - manufacturer=self._manufacturer, - patient_orientation=self._patient_orientation, - transfer_syntax_uid=JPEG2000Lossless + study_instance_uid=study_uid, + series_instance_uid=series_uid, + sop_instance_uid=sop_uid, + series_number=34, + instance_number=7, + manufacturer='ABC', + image_orientation=image_orientation, + pixel_spacing=pixel_spacing, + frame_of_reference_uid=frame_of_reference_uid, ) - assert instance.file_meta.TransferSyntaxUID == JPEG2000Lossless - assert np.array_equal( - self.get_array_after_writing(instance), - frame - ) - - def test_monochrome_jpegls(self): - pytest.importorskip("libjpeg") - bits_allocated = 16 - photometric_interpretation = 'MONOCHROME2' - coordinate_system = 'PATIENT' - frame = np.random.randint(0, 2**16, size=(256, 256), dtype=np.uint16) - instance = SCImage( +def test_construct_with_spatial_info_missing_spacing(): + study_uid = UID() + series_uid = UID() + sop_uid = UID() + frame_of_reference_uid = UID() + photometric_interpretation = 'MONOCHROME2' + coordinate_system = 'PATIENT' + frame = generate_frame( + (10, 10), np.uint16, 0, 16 + ) + image_position = [1, 2, 3] + image_orientation = [1, 0, 0, 0, 1, 0] + msg = ( + "Argument 'pixel_spacing' is required if 'image_position' " + "and 'image_orientation' are provided." + ) + with pytest.raises(TypeError, match=msg): + SCImage( pixel_array=frame, photometric_interpretation=photometric_interpretation, - bits_allocated=bits_allocated, coordinate_system=coordinate_system, - study_instance_uid=self._study_instance_uid, - series_instance_uid=self._series_instance_uid, - sop_instance_uid=self._sop_instance_uid, - series_number=self._series_number, - instance_number=self._instance_number, - manufacturer=self._manufacturer, - patient_orientation=self._patient_orientation, - transfer_syntax_uid=JPEGLSLossless + study_instance_uid=study_uid, + series_instance_uid=series_uid, + sop_instance_uid=sop_uid, + series_number=34, + instance_number=7, + manufacturer='ABC', + image_orientation=image_orientation, + image_position=image_position, + frame_of_reference_uid=frame_of_reference_uid, ) - assert instance.file_meta.TransferSyntaxUID == JPEGLSLossless - - assert np.array_equal( - self.get_array_after_writing(instance), - frame - ) - def test_monochrome_jpegls_near_lossless(self): - pytest.importorskip("libjpeg") - bits_allocated = 16 - photometric_interpretation = 'MONOCHROME2' - coordinate_system = 'PATIENT' - frame = np.random.randint(0, 2**16, size=(256, 256), dtype=np.uint16) - instance = SCImage( +def test_construct_with_spatial_info_missing_ref_uid(): + study_uid = UID() + series_uid = UID() + sop_uid = UID() + photometric_interpretation = 'MONOCHROME2' + coordinate_system = 'PATIENT' + frame = generate_frame( + (10, 10), np.uint16, 0, 16 + ) + image_position = [1, 2, 3] + image_orientation = [1, 0, 0, 0, 1, 0] + pixel_spacing = [1.2, 1.2] + msg = ( + "Argument 'frame_of_reference_uid' is required if " + "'image_position' and 'image_orientation' are provided." + ) + with pytest.raises(TypeError, match=msg): + SCImage( pixel_array=frame, photometric_interpretation=photometric_interpretation, - bits_allocated=bits_allocated, coordinate_system=coordinate_system, - study_instance_uid=self._study_instance_uid, - series_instance_uid=self._series_instance_uid, - sop_instance_uid=self._sop_instance_uid, - series_number=self._series_number, - instance_number=self._instance_number, - manufacturer=self._manufacturer, - patient_orientation=self._patient_orientation, - transfer_syntax_uid=JPEGLSNearLossless + study_instance_uid=study_uid, + series_instance_uid=series_uid, + sop_instance_uid=sop_uid, + series_number=34, + instance_number=7, + manufacturer='ABC', + image_orientation=image_orientation, + image_position=image_position, + pixel_spacing=pixel_spacing, ) - assert instance.file_meta.TransferSyntaxUID == JPEGLSNearLossless - - assert np.allclose( - self.get_array_after_writing(instance), - frame, - atol=2 - ) - def test_rgb_jpegls(self): - pytest.importorskip("libjpeg") - bits_allocated = 8 - photometric_interpretation = 'RGB' - coordinate_system = 'PATIENT' - frame = np.random.randint(0, 256, size=(256, 256, 3), dtype=np.uint8) - instance = SCImage( +def test_construct_with_incosistent_patient_orientation(): + study_uid = UID() + series_uid = UID() + sop_uid = UID() + frame_of_reference_uid = UID() + photometric_interpretation = 'MONOCHROME2' + coordinate_system = 'PATIENT' + frame = generate_frame( + (10, 10), np.uint16, 0, 16 + ) + image_position = [1, 2, 3] + image_orientation = [-1, 0, 0, 0, -1, 0] # R, A + pixel_spacing = [1.2, 1.2] + msg = ( + "The provided 'patient_orientation' is not " + "consistent with the provided value for " + "'image_orientation'." + ) + with pytest.raises(ValueError, match=msg): + SCImage( pixel_array=frame, photometric_interpretation=photometric_interpretation, - bits_allocated=bits_allocated, coordinate_system=coordinate_system, - study_instance_uid=self._study_instance_uid, - series_instance_uid=self._series_instance_uid, - sop_instance_uid=self._sop_instance_uid, - series_number=self._series_number, - instance_number=self._instance_number, - manufacturer=self._manufacturer, - patient_orientation=self._patient_orientation, - transfer_syntax_uid=JPEGLSLossless + study_instance_uid=study_uid, + series_instance_uid=series_uid, + sop_instance_uid=sop_uid, + series_number=34, + instance_number=7, + manufacturer='ABC', + patient_orientation=('L', 'P'), + image_orientation=image_orientation, + image_position=image_position, + pixel_spacing=pixel_spacing, + frame_of_reference_uid=frame_of_reference_uid, ) - assert instance.file_meta.TransferSyntaxUID == JPEGLSLossless - assert np.array_equal( - self.get_array_after_writing(instance), - frame - ) +def test_from_aligned_ref_image(): + file_path = Path(__file__) + data_dir = file_path.parent.parent.joinpath('data') + series_uid = UID() + sop_uid = UID() - def test_construct_rgb_from_ref_dataset(self): - bits_allocated = 8 - photometric_interpretation = 'RGB' - coordinate_system = 'PATIENT' - instance = SCImage.from_ref_dataset( - ref_dataset=self._ref_dataset, - pixel_array=self._rgb_pixel_array, + ref_dataset = dcmread( + str(data_dir.joinpath('test_files', 'ct_image.dcm')) + ) + photometric_interpretation = 'RGB' + frame = generate_frame( + (ref_dataset.Rows, ref_dataset.Columns, 3), np.uint8, 0, 8 + ) + instance = SCImage.from_aligned_ref_image( + ref_image=ref_dataset, + pixel_array=frame, + photometric_interpretation=photometric_interpretation, + series_instance_uid=series_uid, + sop_instance_uid=sop_uid, + series_number=34, + instance_number=7, + manufacturer='ABC', + ) + assert ( + instance.ImageOrientationPatient == + ref_dataset.ImageOrientationPatient + ) + assert ( + instance.ImagePositionPatient == + ref_dataset.ImagePositionPatient + ) + assert ( + instance.PixelSpacing == + ref_dataset.PixelSpacing + ) + assert ( + instance.SliceThickness == + ref_dataset.SliceThickness + ) + assert ( + instance.FrameOfReferenceUID == + ref_dataset.FrameOfReferenceUID + ) + assert ( + instance.PositionReferenceIndicator == + ref_dataset.PositionReferenceIndicator + ) + + +def test_from_aligned_ref_image_wrong_shape(): + file_path = Path(__file__) + data_dir = file_path.parent.parent.joinpath('data') + series_uid = UID() + sop_uid = UID() + + ref_dataset = dcmread( + str(data_dir.joinpath('test_files', 'ct_image.dcm')) + ) + photometric_interpretation = 'RGB' + frame = generate_frame( + # wrong shape + (ref_dataset.Rows - 1, ref_dataset.Columns - 1, 3), + np.uint8, 0, 8 + ) + msg = ( + "Shape of 'pixel_array' must match rows and columns " + "of 'ref_image' when using 'from_aligned_ref_image'." + ) + with pytest.raises(ValueError, match=msg): + SCImage.from_aligned_ref_image( + ref_image=ref_dataset, + pixel_array=frame, photometric_interpretation=photometric_interpretation, - bits_allocated=bits_allocated, - coordinate_system=coordinate_system, - series_instance_uid=self._series_instance_uid, - sop_instance_uid=self._sop_instance_uid, - series_number=self._series_number, - instance_number=self._instance_number, - manufacturer=self._manufacturer, - patient_orientation=self._patient_orientation, - laterality=self._laterality + series_instance_uid=series_uid, + sop_instance_uid=sop_uid, + series_number=34, + instance_number=7, + manufacturer='ABC', ) - assert instance.BitsAllocated == bits_allocated - assert instance.SamplesPerPixel == 3 - assert instance.PlanarConfiguration == 0 - assert instance.PhotometricInterpretation == photometric_interpretation - assert instance.StudyInstanceUID == self._ref_dataset.StudyInstanceUID - assert instance.SeriesInstanceUID == self._series_instance_uid - assert instance.SOPInstanceUID == self._sop_instance_uid - assert instance.SeriesNumber == self._series_number - assert instance.InstanceNumber == self._instance_number - assert instance.Manufacturer == self._manufacturer - assert instance.Laterality == self._laterality - assert instance.PatientOrientation == self._patient_orientation - assert instance.AccessionNumber == self._ref_dataset.AccessionNumber - assert instance.PatientName == self._ref_dataset.PatientName - assert instance.PatientSex == self._ref_dataset.PatientSex - assert instance.StudyTime == TM(self._ref_dataset.StudyTime) - assert instance.StudyDate == DA(self._ref_dataset.StudyDate) - assert instance.StudyID == self._ref_dataset.StudyID - assert instance.PixelData == self._rgb_pixel_array.tobytes() diff --git a/tests/test_seg.py b/tests/test_seg.py index c32099920..5a9d8489f 100644 --- a/tests/test_seg.py +++ b/tests/test_seg.py @@ -28,7 +28,9 @@ ) from highdicom import ( + AnatomicRegion, PaletteColorLUT, + PrimaryAnatomicStructure, PaletteColorLUTTransformation, ) from highdicom.image import _DimensionIndexSequence @@ -50,6 +52,7 @@ create_segmentation_pyramid, segread, SegmentationTypeValues, + SegmentedPropertyType, SegmentAlgorithmTypeValues, Segmentation, SegmentDescription, @@ -167,6 +170,227 @@ def test_malformed_params(self): seq.parameters # noqa: B018 +@pytest.mark.parametrize('from_code', [True, False]) +def test_segmented_property_type_no_modifiers(from_code: bool): + if from_code: + property_type = SegmentedPropertyType(codes.SCT.Tumor) + else: + property_type = SegmentedPropertyType( + CodedConcept.from_code(codes.SCT.Tumor) + ) + + assert isinstance(property_type, CodedConcept) + assert isinstance(property_type.unmodified, CodedConcept) + assert not hasattr( + property_type, + 'SegmentedPropertyTypeModifierCodeSequence' + ) + assert property_type.unmodified == codes.SCT.Tumor + assert property_type.modifiers == () + assert property_type.value == codes.SCT.Tumor.value + assert property_type.meaning == codes.SCT.Tumor.meaning + assert property_type.scheme_designator == codes.SCT.Tumor.scheme_designator + + +@pytest.mark.parametrize('from_code', [True, False]) +def test_segmented_property_type_with_modifiers(from_code: bool): + if from_code: + property_type = SegmentedPropertyType( + codes.SCT.Kidney, + modifiers=[codes.SCT.Left], + ) + else: + property_type = SegmentedPropertyType( + CodedConcept.from_code(codes.SCT.Kidney), + modifiers=[CodedConcept.from_code(codes.SCT.Left)], + ) + + assert isinstance(property_type, CodedConcept) + assert isinstance(property_type.unmodified, CodedConcept) + assert hasattr( + property_type, + 'SegmentedPropertyTypeModifierCodeSequence' + ) + assert len(property_type.SegmentedPropertyTypeModifierCodeSequence) == 1 + assert property_type.unmodified == codes.SCT.Kidney + assert property_type.modifiers == (codes.SCT.Left, ) + assert isinstance(property_type.modifiers[0], CodedConcept) + assert property_type.value == codes.SCT.Kidney.value + assert property_type.meaning == codes.SCT.Kidney.meaning + assert property_type.scheme_designator == codes.SCT.Kidney.scheme_designator + + +def test_segmented_property_type_equality_match(): + property_type_1 = SegmentedPropertyType( + codes.SCT.Kidney, + modifiers=[codes.SCT.Left, codes.SCT.Posterior], + ) + property_type_2 = SegmentedPropertyType( + codes.SCT.Kidney, + modifiers=[codes.SCT.Posterior, codes.SCT.Left], # reverse order + ) + # Test equality operator considers everything equal + assert property_type_1 == property_type_1 + assert property_type_2 == property_type_2 + assert property_type_1 == property_type_2 + + # Test hash operation via comparing sets + assert len({property_type_1, property_type_1}) == 1 + assert len({property_type_1, property_type_2}) == 1 + assert len({property_type_1, property_type_2}) == 1 + + +def test_segmented_property_type_equality_nonmatching(): + property_type_1 = SegmentedPropertyType( + codes.SCT.Kidney, + modifiers=[codes.SCT.Left], + ) + property_type_2 = SegmentedPropertyType( + codes.SCT.Kidney, + ) + + # Test equality operator + assert property_type_1 != property_type_2 + assert property_type_1.unmodified == property_type_2.unmodified + + # Test hash operation via comparing sets + assert len({property_type_1, property_type_2}) == 2 + + +@pytest.mark.parametrize('copy', [True, False]) +def test_segmented_property_type_from_dataset_no_modifiers(copy: bool): + ds = Dataset() + ds.CodeValue = codes.SCT.Tumor.value + ds.CodeMeaning = 'Tumor' + ds.CodingSchemeDesignator = 'SCT' + + property_type = SegmentedPropertyType.from_dataset(ds, copy=copy) + assert isinstance(property_type, SegmentedPropertyType) + assert property_type == codes.SCT.Tumor + assert property_type.modifiers == () + + if copy: + assert property_type is not ds + else: + assert property_type is ds + + +@pytest.mark.parametrize('copy', [True, False]) +def test_segmented_property_type_from_dataset_with_modifiers(copy: bool): + ds = Dataset() + ds.CodeValue = codes.SCT.Kidney.value + ds.CodeMeaning = 'Kidney' + ds.CodingSchemeDesignator = 'SCT' + + modifier = Dataset() + modifier.CodeValue = codes.SCT.Left.value + modifier.CodeMeaning = 'Left' + modifier.CodingSchemeDesignator = 'SCT' + + ds.SegmentedPropertyTypeModifierCodeSequence = [modifier] + + property_type = SegmentedPropertyType.from_dataset(ds, copy=copy) + assert isinstance(property_type, SegmentedPropertyType) + assert property_type.unmodified == codes.SCT.Kidney + assert property_type.modifiers == (codes.SCT.Left, ) + + if copy: + assert property_type is not ds + assert ( + property_type.SegmentedPropertyTypeModifierCodeSequence[0] + is not + ds.SegmentedPropertyTypeModifierCodeSequence[0] + ) + else: + assert property_type is ds + assert ( + property_type.SegmentedPropertyTypeModifierCodeSequence[0] + is + ds.SegmentedPropertyTypeModifierCodeSequence[0] + ) + + +@pytest.mark.parametrize( + 'cls,seq_name', + [ + (AnatomicRegion, 'AnatomicRegionModifierSequence'), + ( + PrimaryAnatomicStructure, + 'PrimaryAnatomicStructureModifierSequence', + ), + ] +) +def test_modified_code_subclasses(cls, seq_name): + plain = cls(codes.SCT.Kidney) + assert plain.modifiers == () + assert not hasattr(plain, seq_name) + + modified = cls(codes.SCT.Kidney, modifiers=[codes.SCT.Left]) + assert len(getattr(modified, seq_name)) == 1 + assert modified.modifiers == (codes.SCT.Left, ) + assert modified.unmodified == codes.SCT.Kidney + assert modified != plain + assert cls.from_code(modified) is modified + assert isinstance(cls.from_code(codes.SCT.Kidney), cls) + + +def test_modified_code_invalid_arguments(): + with pytest.raises(TypeError): + SegmentedPropertyType('not a code') + with pytest.raises(TypeError): + SegmentedPropertyType(codes.SCT.Kidney, modifiers=['not a code']) + + +def test_modified_code_from_other_modified_class_rejected(): + modified = SegmentedPropertyType( + codes.SCT.Kidney, modifiers=[codes.SCT.Left] + ) + with pytest.raises(TypeError): + AnatomicRegion(modified) + with pytest.raises(TypeError): + AnatomicRegion.from_code(modified) + # Even without modifiers, a different class is rejected for consistency + with pytest.raises(TypeError): + PrimaryAnatomicStructure(SegmentedPropertyType(codes.SCT.Kidney)) + + +def test_modified_code_from_same_class_keeps_modifiers(): + modified = SegmentedPropertyType( + codes.SCT.Kidney, modifiers=[codes.SCT.Left] + ) + copied = SegmentedPropertyType(modified) + assert copied == modified + assert copied.modifiers == (codes.SCT.Left, ) + + extended = SegmentedPropertyType( + modified, modifiers=[codes.SCT.Posterior] + ) + assert extended.modifiers == (codes.SCT.Left, codes.SCT.Posterior) + # The original is not altered + assert modified.modifiers == (codes.SCT.Left, ) + + +def test_modified_code_modifiers_not_copied_on_access(): + modified = SegmentedPropertyType( + codes.SCT.Kidney, modifiers=[codes.SCT.Left] + ) + assert modified.modifiers[0] is modified.modifiers[0] + + +def test_modified_code_equality_different_classes(): + # The class of a modified code does not affect equality + a = SegmentedPropertyType(codes.SCT.Kidney, modifiers=[codes.SCT.Left]) + b = AnatomicRegion(codes.SCT.Kidney, modifiers=[codes.SCT.Left]) + assert a == b + assert b == a + assert len({a, b}) == 1 + assert a != AnatomicRegion(codes.SCT.Kidney) + assert a != 'kidney' + # Unmodified compares equal to plain codes + assert SegmentedPropertyType(codes.SCT.Kidney) == codes.SCT.Kidney + assert a != codes.SCT.Kidney + + class TestSegmentDescription(unittest.TestCase): def setUp(self): @@ -399,6 +623,122 @@ def test_construction_mismatched_ids_2(self): tracking_uid=self._tracking_uid, ) + def _make_segment_description(self, **kwargs): + args = { + 'segment_number': 1, + 'segment_label': 'label', + 'segmented_property_category': self._segmented_property_category, + 'segmented_property_type': codes.SCT.Neoplasm, + 'algorithm_type': 'MANUAL', + } + args.update(kwargs) + return SegmentDescription(**args) + + def test_plain_codes_are_converted(self): + item = self._make_segment_description( + anatomic_regions=[codes.SCT.Thorax], + primary_anatomic_structures=[codes.SCT.Lung], + ) + assert isinstance(item.segmented_property_type, SegmentedPropertyType) + assert isinstance(item.anatomic_regions[0], AnatomicRegion) + assert isinstance( + item.primary_anatomic_structures[0], PrimaryAnatomicStructure + ) + assert item.segmented_property_type.modifiers == () + + def test_modifiers(self): + item = self._make_segment_description( + segmented_property_type=SegmentedPropertyType( + codes.SCT.Kidney, modifiers=[codes.SCT.Left] + ), + anatomic_regions=[ + AnatomicRegion(codes.SCT.Thorax, modifiers=[codes.SCT.Right]), + codes.SCT.Abdomen, + ], + primary_anatomic_structures=[ + PrimaryAnatomicStructure( + codes.SCT.Lung, modifiers=[codes.SCT.Left] + ), + ], + ) + ptype = item.SegmentedPropertyTypeCodeSequence[0] + assert ptype.modifiers == (codes.SCT.Left, ) + assert len(ptype.SegmentedPropertyTypeModifierCodeSequence) == 1 + assert item.anatomic_regions[0].modifiers == (codes.SCT.Right, ) + assert item.anatomic_regions[1].modifiers == () + assert len( + item.AnatomicRegionSequence[0].AnatomicRegionModifierSequence + ) == 1 + assert item.primary_anatomic_structures[0].modifiers == ( + codes.SCT.Left, + ) + + def test_empty_sequences_omitted(self): + item = self._make_segment_description( + anatomic_regions=[], + primary_anatomic_structures=[], + ) + assert not hasattr(item, 'AnatomicRegionSequence') + assert not hasattr(item, 'PrimaryAnatomicStructureSequence') + assert item.anatomic_regions == [] + assert item.primary_anatomic_structures == [] + + def test_wrong_modified_type_category(self): + with pytest.raises(TypeError): + self._make_segment_description( + segmented_property_category=SegmentedPropertyType( + self._segmented_property_category + ) + ) + + def test_wrong_modified_type_property_type(self): + with pytest.raises(TypeError): + self._make_segment_description( + segmented_property_type=AnatomicRegion(codes.SCT.Kidney) + ) + + def test_wrong_modified_type_anatomic_region(self): + with pytest.raises(TypeError): + self._make_segment_description( + anatomic_regions=[PrimaryAnatomicStructure(codes.SCT.Lung)] + ) + + def test_wrong_modified_type_primary_anatomic_structure(self): + with pytest.raises(TypeError): + self._make_segment_description( + primary_anatomic_structures=[AnatomicRegion(codes.SCT.Lung)] + ) + + def test_from_dataset_round_trip(self): + item = self._make_segment_description( + segmented_property_type=SegmentedPropertyType( + codes.SCT.Kidney, modifiers=[codes.SCT.Left] + ), + anatomic_regions=[ + AnatomicRegion(codes.SCT.Thorax, modifiers=[codes.SCT.Right]), + ], + primary_anatomic_structures=[ + PrimaryAnatomicStructure( + codes.SCT.Lung, modifiers=[codes.SCT.Left] + ), + ], + ) + ds = Dataset() + ds.SegmentSequence = [item] + ds = write_and_read_dataset(ds) + desc = SegmentDescription.from_dataset(ds.SegmentSequence[0]) + + assert isinstance(desc.segmented_property_type, SegmentedPropertyType) + assert desc.segmented_property_type.modifiers == (codes.SCT.Left, ) + assert isinstance(desc.anatomic_regions[0], AnatomicRegion) + assert desc.anatomic_regions[0].modifiers == (codes.SCT.Right, ) + assert isinstance( + desc.primary_anatomic_structures[0], PrimaryAnatomicStructure + ) + assert desc.primary_anatomic_structures[0].modifiers == ( + codes.SCT.Left, + ) + class TestPixelMeasuresSequence(unittest.TestCase): @@ -4994,6 +5334,198 @@ def test_get_segment_numbers_with_filters(self): ) assert seg_nums == list(self._sm_control_seg.segment_numbers) + def _modified_property_type_seg(self): + """Copy of the control seg with modifiers on segments 2, 3 and 4. + + Segment 1 and 5-20: ConnectiveTissue (no modifiers) + Segment 2: ConnectiveTissue + Left + Segment 3: ConnectiveTissue + Left + Posterior + Segment 4: ConnectiveTissue + Posterior + """ + seg = deepcopy(self._sm_control_seg) + modifiers = { + 2: [codes.SCT.Left], + 3: [codes.SCT.Left, codes.SCT.Posterior], + 4: [codes.SCT.Posterior], + } + for desc in seg.SegmentSequence: + if desc.segment_number in modifiers: + desc.SegmentedPropertyTypeCodeSequence = [ + SegmentedPropertyType( + codes.SCT.ConnectiveTissue, + modifiers=modifiers[desc.segment_number], + ) + ] + return seg + + def test_segmented_property_types_unmodified(self): + types = self._sm_control_seg.segmented_property_types + assert len(types) == 1 + assert isinstance(types[0], SegmentedPropertyType) + assert types[0] == codes.SCT.ConnectiveTissue + assert types[0].modifiers == () + + def test_segmented_property_types_modified(self): + seg = self._modified_property_type_seg() + types = seg.segmented_property_types + + assert all(isinstance(t, SegmentedPropertyType) for t in types) + # Unique by root code and modifiers: plain, Left, Left+Posterior, + # Posterior + assert len(types) == 4 + assert SegmentedPropertyType(codes.SCT.ConnectiveTissue) in types + assert SegmentedPropertyType( + codes.SCT.ConnectiveTissue, modifiers=[codes.SCT.Left] + ) in types + assert SegmentedPropertyType( + codes.SCT.ConnectiveTissue, modifiers=[codes.SCT.Posterior] + ) in types + assert SegmentedPropertyType( + codes.SCT.ConnectiveTissue, + modifiers=[codes.SCT.Posterior, codes.SCT.Left], + ) in types + assert all( + t.unmodified == codes.SCT.ConnectiveTissue for t in types + ) + + def test_segmented_property_types_modified_parsed_from_file(self): + seg = self._modified_property_type_seg() + seg = Segmentation.from_dataset(write_and_read_dataset(seg)) + types = seg.segmented_property_types + assert len(types) == 4 + assert all(isinstance(t, SegmentedPropertyType) for t in types) + assert sum(len(t.modifiers) for t in types) == 4 + + def test_get_segment_numbers_plain_code_ignores_modifiers(self): + seg = self._modified_property_type_seg() + for query in [ + codes.SCT.ConnectiveTissue, + CodedConcept.from_code(codes.SCT.ConnectiveTissue), + ]: + seg_nums = seg.get_segment_numbers( + segmented_property_type=query + ) + assert seg_nums == list(range(1, 21)) + + assert seg.get_segment_numbers( + segmented_property_type=codes.SCT.Lung + ) == [] + + def test_get_segment_numbers_modified_type_no_modifiers(self): + seg = self._modified_property_type_seg() + seg_nums = seg.get_segment_numbers( + segmented_property_type=SegmentedPropertyType( + codes.SCT.ConnectiveTissue + ) + ) + assert seg_nums == [1] + list(range(5, 21)) + + def test_get_segment_numbers_modified_type_single_modifier(self): + seg = self._modified_property_type_seg() + seg_nums = seg.get_segment_numbers( + segmented_property_type=SegmentedPropertyType( + codes.SCT.ConnectiveTissue, + modifiers=[codes.SCT.Left], + ) + ) + assert seg_nums == [2] + + def test_get_segment_numbers_modified_type_multiple_modifiers(self): + seg = self._modified_property_type_seg() + # Order of modifiers is not significant + for modifiers in ( + [codes.SCT.Left, codes.SCT.Posterior], + [codes.SCT.Posterior, codes.SCT.Left], + ): + seg_nums = seg.get_segment_numbers( + segmented_property_type=SegmentedPropertyType( + codes.SCT.ConnectiveTissue, + modifiers=modifiers, + ) + ) + assert seg_nums == [3] + + def test_get_segment_numbers_modified_type_no_match(self): + seg = self._modified_property_type_seg() + # Wrong root code + assert seg.get_segment_numbers( + segmented_property_type=SegmentedPropertyType( + codes.SCT.Lung, + modifiers=[codes.SCT.Left], + ) + ) == [] + # Modifier not present on any segment + assert seg.get_segment_numbers( + segmented_property_type=SegmentedPropertyType( + codes.SCT.ConnectiveTissue, + modifiers=[codes.SCT.Right], + ) + ) == [] + # Superset of a segment's modifiers does not match + assert seg.get_segment_numbers( + segmented_property_type=SegmentedPropertyType( + codes.SCT.ConnectiveTissue, + modifiers=[ + codes.SCT.Left, codes.SCT.Posterior, codes.SCT.Right + ], + ) + ) == [] + + def test_get_segment_numbers_modified_type_combined_filters(self): + seg = self._modified_property_type_seg() + seg_nums = seg.get_segment_numbers( + segmented_property_category=codes.SCT.Tissue, + segmented_property_type=SegmentedPropertyType( + codes.SCT.ConnectiveTissue, + modifiers=[codes.SCT.Posterior], + ), + algorithm_type=SegmentAlgorithmTypeValues.AUTOMATIC, + ) + assert seg_nums == [4] + + seg_nums = seg.get_segment_numbers( + segmented_property_type=SegmentedPropertyType( + codes.SCT.ConnectiveTissue, + modifiers=[codes.SCT.Posterior], + ), + tracking_id=seg.get_segment_description(1).tracking_id, + ) + assert seg_nums == [] + + def test_get_segment_numbers_modified_type_parsed_from_file(self): + # Modifiers survive a write/read round trip through the dataset + seg = self._modified_property_type_seg() + seg = Segmentation.from_dataset(write_and_read_dataset(seg)) + seg_nums = seg.get_segment_numbers( + segmented_property_type=SegmentedPropertyType( + codes.SCT.ConnectiveTissue, + modifiers=[codes.SCT.Left], + ) + ) + assert seg_nums == [2] + assert seg.get_segment_numbers( + segmented_property_type=codes.SCT.ConnectiveTissue + ) == list(range(1, 21)) + + def test_get_tracking_ids_modified_type(self): + seg = self._modified_property_type_seg() + + # Plain code matches ignoring modifiers + assert len(seg.get_tracking_ids( + segmented_property_type=codes.SCT.ConnectiveTissue + )) == 20 + + tracking_id_tuples = seg.get_tracking_ids( + segmented_property_type=SegmentedPropertyType( + codes.SCT.ConnectiveTissue, + modifiers=[codes.SCT.Left], + ) + ) + desc2 = seg.get_segment_description(2) + assert tracking_id_tuples == [ + (desc2.tracking_id, desc2.tracking_uid) + ] + def test_get_tracking_ids(self): desc1 = self._sm_control_seg.get_segment_description(1) diff --git a/tests/test_sr.py b/tests/test_sr.py index 30a364da6..81680e4b5 100644 --- a/tests/test_sr.py +++ b/tests/test_sr.py @@ -12,6 +12,7 @@ from pydicom.data import get_testdata_file, get_testdata_files from pydicom.dataset import Dataset from pydicom.filereader import dcmread +from pydicom.sequence import Sequence as DicomSequence from pydicom.sr.codedict import codes from pydicom.sr.coding import Code from pydicom.uid import generate_uid @@ -22,6 +23,7 @@ AlgorithmIdentification, CodeContentItem, CodedConcept, + codes_equal, CompositeContentItem, Comprehensive3DSR, ComprehensiveSR, @@ -70,6 +72,7 @@ SubjectContextSpecimen, TcoordContentItem, TextContentItem, + TextEvaluation, TimeContentItem, TimePointContext, TrackingIdentifier, @@ -80,6 +83,9 @@ WaveformContentItem, srread, ) +from highdicom import AnatomicRegion +from highdicom.ann import AnnotatedPropertyType +from highdicom.seg import SegmentedPropertyType from highdicom.sr.content import CoordinatesForMeasurement from highdicom.sr.utils import find_content_items from highdicom import UID @@ -720,6 +726,178 @@ def test_equal_equivalent_coding(self): assert c1 == c2 +class TestCodesEqual: + + @staticmethod + @pytest.fixture( + params=[ + SegmentedPropertyType, + AnatomicRegion, + AnnotatedPropertyType, + ] + ) + def modified_class(request): + return request.param + + def test_plain_codes(self): + concept = CodedConcept.from_code(codes.SCT.Kidney) + for a, b in [ + (codes.SCT.Kidney, codes.SCT.Kidney), + (codes.SCT.Kidney, concept), + (concept, codes.SCT.Kidney), + (concept, concept), + ]: + assert codes_equal(a, b) + + assert not codes_equal(codes.SCT.Kidney, codes.SCT.Liver) + assert not codes_equal(concept, codes.SCT.Liver) + + def test_meaning_ignored(self): + a = Code('64033007', 'SCT', 'Kidney') + b = Code('64033007', 'SCT', 'Something else') + assert codes_equal(a, b) + + def test_equivalent_coding(self): + a = CodedConcept('373098007', 'SCT', 'Mean Value of population') + b = CodedConcept('R-00317', 'SRT', 'Mean Value of population') + assert codes_equal(a, b) + assert codes_equal(b, a) + + def test_invalid_types(self): + with pytest.raises(TypeError): + codes_equal(codes.SCT.Kidney, 'kidney') + with pytest.raises(TypeError): + codes_equal(None, codes.SCT.Kidney) + + def test_modifiers_significant_by_default(self, modified_class): + modified = modified_class(codes.SCT.Kidney, modifiers=[codes.SCT.Left]) + unmodified = modified_class(codes.SCT.Kidney) + other_modified = modified_class( + codes.SCT.Kidney, modifiers=[codes.SCT.Right] + ) + + assert codes_equal(modified, modified) + assert codes_equal(unmodified, codes.SCT.Kidney) + assert not codes_equal(modified, unmodified) + assert not codes_equal(modified, other_modified) + + def test_symmetric_with_pydicom_code(self, modified_class): + modified = modified_class(codes.SCT.Kidney, modifiers=[codes.SCT.Left]) + unmodified = modified_class(codes.SCT.Kidney) + + assert not codes_equal(modified, codes.SCT.Kidney) + assert not codes_equal(codes.SCT.Kidney, modified) + + assert codes_equal(unmodified, codes.SCT.Kidney) + assert codes_equal(codes.SCT.Kidney, unmodified) + + def test_ignore_modifiers(self, modified_class): + modified = modified_class(codes.SCT.Kidney, modifiers=[codes.SCT.Left]) + other_modified = modified_class( + codes.SCT.Kidney, modifiers=[codes.SCT.Right] + ) + for a, b in [ + (modified, codes.SCT.Kidney), + (codes.SCT.Kidney, modified), + (modified, other_modified), + (modified, CodedConcept.from_code(codes.SCT.Kidney)), + ]: + assert codes_equal(a, b, ignore_modifiers=True) + + assert not codes_equal( + modified, + codes.SCT.Liver, + ignore_modifiers=True, + ) + + def test_modifier_order_not_significant(self, modified_class): + a = modified_class( + codes.SCT.Kidney, + modifiers=[codes.SCT.Left, codes.SCT.Posterior], + ) + b = modified_class( + codes.SCT.Kidney, + modifiers=[codes.SCT.Posterior, codes.SCT.Left], + ) + assert codes_equal(a, b) + assert codes_equal(b, a) + + def test_modifier_subset_not_equal(self, modified_class): + a = modified_class( + codes.SCT.Kidney, + modifiers=[codes.SCT.Left, codes.SCT.Posterior], + ) + b = modified_class(codes.SCT.Kidney, modifiers=[codes.SCT.Left]) + assert not codes_equal(a, b) + assert not codes_equal(b, a) + + def test_class_not_considered(self): + a = SegmentedPropertyType(codes.SCT.Kidney, modifiers=[codes.SCT.Left]) + b = AnatomicRegion(codes.SCT.Kidney, modifiers=[codes.SCT.Left]) + c = AnnotatedPropertyType(codes.SCT.Kidney, modifiers=[codes.SCT.Left]) + assert codes_equal(a, b) + assert codes_equal(b, c) + assert codes_equal(a, c) + + def test_equivalent_modifiers_match(self, modified_class): + a = modified_class( + codes.SCT.Kidney, + modifiers=[CodedConcept('373098007', 'SCT', 'Mean')], + ) + b = modified_class( + codes.SCT.Kidney, + modifiers=[CodedConcept('R-00317', 'SRT', 'Mean')], + ) + assert codes_equal(a, b) + + def test_operator_agrees_with_function(self, modified_class): + concepts = [ + modified_class(codes.SCT.Kidney), + modified_class(codes.SCT.Kidney, modifiers=[codes.SCT.Left]), + modified_class( + codes.SCT.Kidney, + modifiers=[codes.SCT.Left, codes.SCT.Posterior], + ), + modified_class(codes.SCT.Liver), + CodedConcept.from_code(codes.SCT.Kidney), + ] + for a in concepts: + for b in concepts: + assert (a == b) == codes_equal(a, b) + assert (a != b) == (not codes_equal(a, b)) + + def test_hash_consistent_with_equality(self, modified_class): + concepts = [ + modified_class(codes.SCT.Kidney), + modified_class(codes.SCT.Kidney, modifiers=[codes.SCT.Left]), + modified_class( + codes.SCT.Kidney, + modifiers=[codes.SCT.Posterior, codes.SCT.Left], + ), + modified_class( + codes.SCT.Kidney, + modifiers=[codes.SCT.Left, codes.SCT.Posterior], + ), + modified_class(codes.SCT.Liver), + CodedConcept.from_code(codes.SCT.Kidney), + codes.SCT.Kidney, + ] + for a in concepts: + for b in concepts: + if a == b and b == a: + assert hash(a) == hash(b) + + def test_operator_asymmetry_with_pydicom_code(self, modified_class): + # Documents known behavior: pydicom's Code.__eq__ is evaluated first + # when a Code is the left operand and knows nothing of modifiers. + # codes_equal should be used instead in such situations. + modified = modified_class(codes.SCT.Kidney, modifiers=[codes.SCT.Left]) + assert modified != codes.SCT.Kidney + assert codes.SCT.Kidney == modified + assert not codes_equal(modified, codes.SCT.Kidney) + assert not codes_equal(codes.SCT.Kidney, modified) + + class TestContentItem(unittest.TestCase): def setUp(self): @@ -3345,6 +3523,264 @@ def test_construction(self): assert len(evaluation) == 1 assert evaluation.name == self._name assert evaluation.value == self._value + assert evaluation.modifiers == [] + assert not hasattr(evaluation[0], 'ContentSequence') + + def _make_modifier(self, relationship_type=None): + return CodeContentItem( + name=codes.SCT.Severity, + value=codes.SCT.Severe, + relationship_type=relationship_type, + ) + + def test_construction_with_modifiers(self): + modifier = self._make_modifier( + RelationshipTypeValues.HAS_CONCEPT_MOD + ) + evaluation = QualitativeEvaluation( + name=self._name, + value=self._value, + modifiers=[modifier], + ) + + assert len(evaluation) == 1 + assert len(evaluation[0].ContentSequence) == 1 + modifiers = evaluation.modifiers + assert len(modifiers) == 1 + assert isinstance(modifiers[0], CodeContentItem) + assert modifiers[0].name == codes.SCT.Severity + assert modifiers[0].value == codes.SCT.Severe + assert modifiers[0].relationship_type == ( + RelationshipTypeValues.HAS_CONCEPT_MOD + ) + + def test_construction_with_modifiers_string_relationship_type(self): + modifier = self._make_modifier('HAS CONCEPT MOD') + evaluation = QualitativeEvaluation( + name=self._name, + value=self._value, + modifiers=[modifier], + ) + assert len(evaluation.modifiers) == 1 + + def test_construction_with_modifiers_no_relationship_type(self): + modifier = self._make_modifier() + evaluation = QualitativeEvaluation( + name=self._name, + value=self._value, + modifiers=[modifier], + ) + + modifiers = evaluation.modifiers + assert len(modifiers) == 1 + assert isinstance(modifiers[0], CodeContentItem) + assert modifiers[0].relationship_type == ( + RelationshipTypeValues.HAS_CONCEPT_MOD + ) + + def test_construction_with_empty_modifiers(self): + evaluation = QualitativeEvaluation( + name=self._name, + value=self._value, + modifiers=[], + ) + assert evaluation.modifiers == [] + assert not hasattr(evaluation[0], 'ContentSequence') + + def test_construction_with_modifiers_wrong_relationship_type(self): + modifier = self._make_modifier(RelationshipTypeValues.CONTAINS) + msg = ( + "Items of 'modifiers' must have relationship type " + "'HAS CONCEPT MOD'." + ) + with pytest.raises(ValueError, match=msg): + QualitativeEvaluation( + name=self._name, + value=self._value, + modifiers=[modifier], + ) + + def test_construction_with_modifiers_wrong_type(self): + modifier = TextContentItem( + name=codes.SCT.Severity, + value='severe', + relationship_type=RelationshipTypeValues.HAS_CONCEPT_MOD, + ) + msg = ( + "Items of 'modifiers' must have type " + "highdicom.sr.CodeContentItem." + ) + with pytest.raises(TypeError, match=msg): + QualitativeEvaluation( + name=self._name, + value=self._value, + modifiers=[modifier], + ) + + def test_construction_with_code_modifier_wrong_type(self): + msg = ( + "Items of 'modifiers' must have type " + "highdicom.sr.CodeContentItem." + ) + with pytest.raises(TypeError, match=msg): + QualitativeEvaluation( + name=self._name, + value=self._value, + modifiers=[codes.SCT.Severe], + ) + + @staticmethod + def _make_code_dataset(code): + ds = Dataset() + ds.CodeValue = code.value + ds.CodingSchemeDesignator = code.scheme_designator + ds.CodeMeaning = code.meaning + return ds + + def _make_code_item_dataset(self, name, value, relationship_type): + ds = Dataset() + ds.RelationshipType = relationship_type + ds.ValueType = 'CODE' + ds.ConceptNameCodeSequence = [self._make_code_dataset(name)] + ds.ConceptCodeSequence = [self._make_code_dataset(value)] + return ds + + def _make_evaluation_sequence(self, modifiers=None): + item = self._make_code_item_dataset( + self._name, + self._value, + 'CONTAINS', + ) + if modifiers is not None: + item.ContentSequence = DicomSequence(modifiers) + + return DicomSequence([item]) + + def test_from_sequence(self): + sequence = self._make_evaluation_sequence() + parsed = QualitativeEvaluation.from_sequence(sequence) + + assert isinstance(parsed, QualitativeEvaluation) + assert parsed.name == self._name + assert parsed.value == self._value + assert parsed.modifiers == [] + assert not hasattr(parsed[0], 'ContentSequence') + + def test_from_sequence_with_modifiers(self): + sequence = self._make_evaluation_sequence( + modifiers=[ + self._make_code_item_dataset( + codes.SCT.Severity, + codes.SCT.Severe, + 'HAS CONCEPT MOD', + ), + self._make_code_item_dataset( + codes.SCT.Severity, + codes.SCT.Mild, + 'HAS CONCEPT MOD', + ), + ] + ) + parsed = QualitativeEvaluation.from_sequence(sequence) + + assert parsed.name == self._name + assert parsed.value == self._value + # Modifiers must be encoded in the content item itself + assert len(parsed[0].ContentSequence) == 2 + modifiers = parsed.modifiers + assert len(modifiers) == 2 + assert all(isinstance(m, CodeContentItem) for m in modifiers) + assert modifiers[0].name == codes.SCT.Severity + assert modifiers[0].value == codes.SCT.Severe + assert modifiers[1].value == codes.SCT.Mild + assert all( + m.relationship_type == RelationshipTypeValues.HAS_CONCEPT_MOD + for m in modifiers + ) + + def test_from_sequence_ignores_non_modifier_children(self): + comment = Dataset() + comment.RelationshipType = 'HAS PROPERTIES' + comment.ValueType = 'TEXT' + comment.ConceptNameCodeSequence = [ + self._make_code_dataset(codes.DCM.Comment) + ] + comment.TextValue = 'a comment' + sequence = self._make_evaluation_sequence( + modifiers=[ + self._make_code_item_dataset( + codes.SCT.Severity, + codes.SCT.Severe, + 'HAS CONCEPT MOD', + ), + # CODE item, but not a modifier relationship + self._make_code_item_dataset( + codes.SCT.Severity, + codes.SCT.Mild, + 'HAS PROPERTIES', + ), + comment, + ] + ) + parsed = QualitativeEvaluation.from_sequence(sequence) + + assert len(parsed.modifiers) == 1 + assert parsed.modifiers[0].value == codes.SCT.Severe + assert len(parsed[0].ContentSequence) == 1 + + +class TestTextEvaluation(unittest.TestCase): + + def setUp(self): + self._name = codes.DCM.Impression + self._value = 'Likely benign, recommend follow-up in 12 months' + + def test_construction(self): + evaluation = TextEvaluation( + name=self._name, + value=self._value, + ) + + assert len(evaluation) == 1 + item = evaluation[0] + assert isinstance(item, TextContentItem) + assert item.relationship_type == RelationshipTypeValues.CONTAINS + assert evaluation.name == self._name + assert evaluation.value == self._value + + def test_from_sequence(self): + item = Dataset() + item.RelationshipType = 'CONTAINS' + item.ValueType = 'TEXT' + concept_name = Dataset() + concept_name.CodeValue = self._name.value + concept_name.CodingSchemeDesignator = self._name.scheme_designator + concept_name.CodeMeaning = self._name.meaning + item.ConceptNameCodeSequence = [concept_name] + item.TextValue = self._value + sequence = DicomSequence([item]) + + parsed = TextEvaluation.from_sequence(sequence) + + assert isinstance(parsed, TextEvaluation) + assert parsed.name == self._name + assert parsed.value == self._value + + def test_from_sequence_wrong_value_type(self): + evaluation = QualitativeEvaluation( + name=codes.SCT.AssociatedMorphology, + value=codes.SCT.Neoplasm, + ) + with pytest.raises(ValueError): + TextEvaluation.from_sequence(evaluation) + + def test_from_sequence_multiple_items(self): + evaluation = TextEvaluation(name=self._name, value=self._value) + with pytest.raises( + ValueError, + match='Text Evaluation shall contain only one content item.' + ): + TextEvaluation.from_sequence([evaluation[0], evaluation[0]]) class TestMeasurementsAndQualitativeEvaluations(unittest.TestCase): @@ -3435,6 +3871,124 @@ def test_get_measurements_and_evaluations_with_context(self): ) assert group.finding_type == codes.SCT.Neoplasm + def test_get_evaluations_with_modifiers(self): + qualitative_evaluations = [ + QualitativeEvaluation( + name=codes.SCT.AssociatedMorphology, + value=codes.SCT.Neoplasm, + modifiers=[ + CodeContentItem( + name=codes.SCT.Severity, + value=codes.SCT.Severe, + ), + ], + ), + ] + template = MeasurementsAndQualitativeEvaluations( + tracking_identifier=self._tracking_identifier, + measurements=self._measurements, + qualitative_evaluations=qualitative_evaluations, + ) + parsed = MeasurementsAndQualitativeEvaluations.from_sequence(template) + for group in (template, parsed): + # The modifier is nested and must not show up as a separate + # qualitative evaluation + evaluations = group.get_qualitative_evaluations() + assert len(evaluations) == 1 + evaluation = evaluations[0] + assert evaluation.name == codes.SCT.AssociatedMorphology + assert evaluation.value == codes.SCT.Neoplasm + modifiers = evaluation.modifiers + assert len(modifiers) == 1 + assert modifiers[0].name == codes.SCT.Severity + assert modifiers[0].value == codes.SCT.Severe + + # Modifiers must survive re-use of a retrieved evaluation in a + # new measurement group + regrouped = MeasurementsAndQualitativeEvaluations( + tracking_identifier=self._tracking_identifier, + measurements=self._measurements, + qualitative_evaluations=evaluations, + ) + reevaluations = regrouped.get_qualitative_evaluations() + assert len(reevaluations) == 1 + assert len(reevaluations[0].modifiers) == 1 + + def test_get_text_evaluations(self): + text_evaluations = [ + TextEvaluation( + name=codes.DCM.Impression, + value='Likely benign', + ), + TextEvaluation( + name=codes.DCM.Comment, + value='Compare with prior study', + ), + ] + # Include other TEXT content items in the group (tracking identifier, + # session, time point and algorithm identification), which must not + # be returned as text evaluations + template = MeasurementsAndQualitativeEvaluations( + tracking_identifier=self._tracking_identifier, + session='Session 1', + time_point_context=TimePointContext(time_point='first'), + algorithm_id=AlgorithmIdentification( + name='algo', + version='1.0', + ), + measurements=self._measurements, + qualitative_evaluations=[ + QualitativeEvaluation( + name=codes.SCT.AssociatedMorphology, + value=codes.SCT.Neoplasm, + ), + ], + text_evaluations=text_evaluations, + ) + parsed = MeasurementsAndQualitativeEvaluations.from_sequence(template) + for group in (template, parsed): + evaluations = group.get_text_evaluations() + assert len(evaluations) == 2 + assert all(isinstance(e, TextEvaluation) for e in evaluations) + assert evaluations[0].name == codes.DCM.Impression + assert evaluations[0].value == 'Likely benign' + assert evaluations[1].name == codes.DCM.Comment + assert evaluations[1].value == 'Compare with prior study' + + filtered = group.get_text_evaluations(name=codes.DCM.Comment) + assert len(filtered) == 1 + assert filtered[0].value == 'Compare with prior study' + + assert group.get_text_evaluations(name=codes.DCM.Finding) == [] + + # Text evaluations must not interfere with coded evaluations + assert len(group.get_qualitative_evaluations()) == 1 + + def test_get_text_evaluations_empty(self): + template = MeasurementsAndQualitativeEvaluations( + tracking_identifier=self._tracking_identifier, + session='Session 1', + measurements=self._measurements, + ) + assert template.get_text_evaluations() == [] + + def test_construction_with_text_evaluations_wrong_type(self): + msg = ( + 'Items of argument "text_evaluations" must have type ' + 'TextEvaluation.' + ) + with pytest.raises(TypeError, match=msg): + MeasurementsAndQualitativeEvaluations( + tracking_identifier=self._tracking_identifier, + text_evaluations=[ + TextContentItem( + name=codes.DCM.Comment, + value='a comment', + relationship_type=RelationshipTypeValues.CONTAINS, + ) + ], + ) + class TestPlanarROIMeasurementsAndQualitativeEvaluations(unittest.TestCase): @@ -3534,6 +4088,26 @@ def test_construction_with_region(self): assert root_item.ContentTemplateSequence[0].TemplateIdentifier == '1410' assert template.reference_type == codes.DCM.ImageRegion + def test_construction_with_text_evaluations(self): + template = PlanarROIMeasurementsAndQualitativeEvaluations( + tracking_identifier=self._tracking_identifier, + referenced_region=self._region, + text_evaluations=[ + TextEvaluation( + name=codes.DCM.Comment, + value='Poorly defined margin', + ), + ], + ) + parsed = PlanarROIMeasurementsAndQualitativeEvaluations.from_sequence( + template + ) + for group in (template, parsed): + evaluations = group.get_text_evaluations() + assert len(evaluations) == 1 + assert evaluations[0].name == codes.DCM.Comment + assert evaluations[0].value == 'Poorly defined margin' + def test_construction_with_region_3d(self): template = PlanarROIMeasurementsAndQualitativeEvaluations( tracking_identifier=self._tracking_identifier, @@ -3784,6 +4358,25 @@ def test_constructed_with_regions(self): assert template.referenced_segment is None assert template.reference_type == codes.DCM.ImageRegion + def test_constructed_with_text_evaluations(self): + cls = VolumetricROIMeasurementsAndQualitativeEvaluations + template = cls( + tracking_identifier=self._tracking_identifier, + referenced_regions=self._regions, + text_evaluations=[ + TextEvaluation( + name=codes.DCM.Comment, + value='Heterogeneous enhancement', + ), + ], + ) + parsed = cls.from_sequence(template) + for group in (template, parsed): + evaluations = group.get_text_evaluations() + assert len(evaluations) == 1 + assert evaluations[0].name == codes.DCM.Comment + assert evaluations[0].value == 'Heterogeneous enhancement' + def test_constructed_with_regions_3d(self): with pytest.raises(TypeError): VolumetricROIMeasurementsAndQualitativeEvaluations( diff --git a/tests/test_volume.py b/tests/test_volume.py index b79de9968..9cd1055d5 100644 --- a/tests/test_volume.py +++ b/tests/test_volume.py @@ -943,6 +943,55 @@ def test_match_geometry_failure_translation(): vol.match_geometry(geometry) +def test_match_geometry_small_translation_within_tolerance(): + vol, _ = read_multiframe_ct_volume() + # Misalignment of 0.1% of a voxel along the row direction + shift = 1e-3 * vol.spacing[1] + + new_affine = _translate_affine_matrix(vol.affine, [0.0, shift, 0.0]) + geometry = VolumeGeometry( + new_affine, + vol.shape, + coordinate_system="PATIENT", + ) + + matched = vol.match_geometry(geometry) + assert matched.spatial_shape == vol.spatial_shape + + with pytest.raises(RuntimeError): + vol.match_geometry(geometry, position_tol=1e-5) + + +def test_match_geometry_far_corner_drift(): + vol, _ = read_multiframe_ct_volume() + n = vol.spatial_shape[2] + + # Spacing error passes spacing_tol per voxel, but accumulates across + # the extent of the volume to well over position_tol + new_affine = vol.affine.copy() + new_affine[:3, 2] *= 1.0 + 5e-4 + geometry = VolumeGeometry( + new_affine, + vol.shape, + coordinate_system="PATIENT", + ) + assert (n - 1) * 5e-4 > 1e-2 + + with pytest.raises(RuntimeError, match="drift"): + vol.match_geometry(geometry) + + # Passes when the tolerance is loosened accordingly + vol.match_geometry(geometry, position_tol=1.0) + + +def test_match_geometry_deprecated_tol(): + vol, _ = read_multiframe_ct_volume() + geometry = vol.get_geometry() + + with pytest.warns(DeprecationWarning): + vol.match_geometry(geometry, tol=1e-5) + + def test_match_geometry_failure_spacing(): vol, _ = read_multiframe_ct_volume()