Beispiel #1
0
    def __getattr__(self, name):
        # for codes.X, X must be a CID or a scheme designator
        if name.startswith("cid"):
            if not self.scheme:
                return _CID_Dict(int(name[3:]))
            raise AttributeError("Cannot call cid selector on scheme dict")
        if name in self._dict.keys():
            # Return concepts limited only the specified scheme designator
            return _CodesDict(scheme=name)

        # If not already narrowed to a particular scheme, is an error
        if not self.scheme:
            msg = "'{}' not recognized as a CID or scheme designator"
            raise AttributeError(msg.format(name))

        # else try to find in this scheme
        scheme = self.scheme
        try:
            val = self._dict[scheme][name]
        except KeyError:
            msg = "Unknown code name '{}' for scheme '{}'"
            raise AttributeError(msg.format(name, scheme))
        # val is like {code1: (meaning, cid_list}, code2: ...}
        if len(val) > 1:  # more than one code for this name
            raise NotImplementedError("Need cid to disambiguate")
        else:
            code = list(val.keys())[0]  # get first and only
            meaning, cids = val[code]
            return Code(value=code, meaning=meaning, scheme_designator=scheme)
 def test_construction_args_optional(self):
     version = "v1.0"
     c = Code(self._value, self._scheme_designator, self._meaning, version)
     assert c.value == self._value
     assert c.scheme_designator == self._scheme_designator
     assert c.meaning == self._meaning
     assert c.scheme_version == version
Beispiel #3
0
    def __getattr__(self, name: str) -> Union["_CodesDict", _CID_Dict, Code]:
        """Return either a ``_CodesDict``, ``_CID_Dict`` or ``Code`` depending
        on the `name`.

        Parameters
        ----------
        name : str
            One of the following:

            * A coding scheme designator such as ``"SCT"``.
            * A concept ID such as ``"CID2"``.
            * If ``_CodesDict.scheme`` is not ``None``, a camel case version
              of the concept's code meaning, such as ``"FontanelOfSkull" in
              the SCT coding scheme.

        Returns
        -------
        pydicom.sr._CodesDict, pydicom.sr._CID_Dict or pydicom.sr.Code

            * If `name` is a concept ID then the ``_CID_Dict`` for the
              corresponding CID.
            * If `name` is a coding scheme designator then the ``_CodesDict``
              instance for the corresponding scheme.
            * If ``_CodesDict.scheme`` is not ``None`` then the ``Code``
              corresponding to `name`.
        """
        # for codes.X, X must be a CID or a scheme designator
        if name.startswith("cid"):
            if not self.scheme:
                return _CID_Dict(int(name[3:]))

            raise AttributeError("Cannot use a CID with a scheme dictionary")

        if name in self._dict.keys():
            # Return concepts limited only the specified scheme designator
            return _CodesDict(scheme=name)

        # If not already narrowed to a particular scheme, is an error
        if not self.scheme:
            raise AttributeError(
                f"'{name}' not recognized as a CID or scheme designator")

        # else try to find in this scheme
        try:
            val = cast(Dict[str, Tuple[str, List[int]]],
                       self._dict[self.scheme][name])
        except KeyError:
            raise AttributeError(
                f"Unknown code name '{name}' for scheme '{self.scheme}'")

        if len(val) > 1:
            # val is {code value: (meaning, cid_list}, code_value: ...}
            code_values = ", ".join(val.keys())
            raise RuntimeError(
                f"Multiple code values for '{name}' found: {code_values}")

        code = list(val.keys())[0]  # get first and only
        meaning, cids = val[code]

        return Code(value=code, meaning=meaning, scheme_designator=self.scheme)
Beispiel #4
0
 def __getattr__(self, name):
     matches = [
         scheme for scheme, keywords in cid_concepts[self.cid].items()
         if name in keywords
     ]
     if not matches:
         msg = "Identifier '{}' not found for cid{}".format(name, self.cid)
         raise AttributeError(msg)
     elif len(matches) > 1:
         # Should never happen, but just in case
         msg = "Multiple schemes found for '{}' in cid{}".format(name, cid)
         raise AssertionError(msg)
     else:
         scheme = matches[0]
         concept = concepts[scheme][name]
         # Almost always only one code per concepts name
         if len(concept) == 1:
             code, val = list(concept.items())[0]
         else:
             matches = [(code, val) for code, val in concept.items()
                        if self.cid in val[1]]
             if len(matches) > 1:
                 # Should never happen, but check in case
                 msg = "{} had multiple code matches for cid{}".format(
                     name, cid)
                 raise AssertionError(msg)
             code, val = matches[0]
         return Code(value=code, meaning=val[0], scheme_designator=scheme)
Beispiel #5
0
 def test_use_as_dictionary_key(self):
     c = Code(
         value=self._value,
         scheme_designator=self._scheme_designator,
         meaning=self._meaning,
     )
     d = {c: 1}
     assert c in d.keys()
Beispiel #6
0
 def test_cid3263(self):
     meaning = ("12-lead from EASI leads (ES, AS, AI)"
                " by Dower/EASI transformation")
     assert (codes.cid3263.
             _12LeadFromEASILeadsESASAIByDowerEASITransformation == Code(
                 value="10:11284",
                 scheme_designator="MDC",
                 meaning=meaning,
             ))
 def test_construction_kwargs(self):
     c = Code(
         value=self._value,
         scheme_designator=self._scheme_designator,
         meaning=self._meaning,
     )
     assert c.value == self._value
     assert c.scheme_designator == self._scheme_designator
     assert c.meaning == self._meaning
     assert c.scheme_version is None
Beispiel #8
0
 def test_num_item_construction_from_qualifier_code(self):
     name = codes.SCT.Area
     qualifier = Code('114000', 'SCT', 'Not a number')
     i = NumContentItem(name=name, qualifier=qualifier)
     assert i.ValueType == 'NUM'
     assert i.ConceptNameCodeSequence[0] == name
     with pytest.raises(AttributeError):
         assert i.MeasuredValueSequence
     with pytest.raises(AttributeError):
         assert i.RelationshipType
     qualifier_code_item = i.NumericValueQualifierCodeSequence[0]
     assert qualifier_code_item.CodeValue == qualifier.value
Beispiel #9
0
    def __eq__(self, other):
        """Compares `self` and `other` for equality.

        Parameters
        ----------
        other: Union[pydicom.sr.coding.CodedConcept, pydicom.sr.coding.Code]
            code

        Returns
        -------
        bool
            whether `self` and `other` are considered equal

        """
        return Code.__eq__(self, other)
Beispiel #10
0
 def test_num_item_construction_from_float(self):
     name = codes.SCT.Area
     value = 100.0
     unit = Code('um2', 'UCUM', 'Square Micrometer')
     i = NumContentItem(name=name, value=value, unit=unit)
     assert i.ValueType == 'NUM'
     assert i.ConceptNameCodeSequence[0] == name
     value_item = i.MeasuredValueSequence[0]
     unit_code_item = value_item.MeasurementUnitsCodeSequence[0]
     assert value_item.NumericValue == value
     assert value_item.FloatingPointValue == value
     assert unit_code_item.CodeValue == unit.value
     assert unit_code_item.CodingSchemeDesignator == unit.scheme_designator
     with pytest.raises(AttributeError):
         assert i.RelationshipType
     with pytest.raises(AttributeError):
         assert i.NumericValueQualifierCodeSequence
Beispiel #11
0
    def __getattr__(self, name: str) -> Code:
        """Return the ``Code`` for class attribute `name`."""
        matches = [
            scheme for scheme, keywords in CID_CONCEPTS[self.cid].items()
            if name in keywords
        ]

        if not matches:
            raise AttributeError(f"'{name}' not found in CID {self.cid}")

        if len(matches) > 1:
            # Should never happen, but just in case
            raise AttributeError(
                f"Multiple schemes found for '{name}' in CID {self.cid}: "
                f"{', '.join(matches)}")

        scheme = matches[0]
        identifiers = cast(Dict[str, Tuple[str, List[int]]],
                           CONCEPTS[scheme][name])
        # Almost always only one code per identifier
        if len(identifiers) == 1:
            code, val = list(identifiers.items())[0]
        else:
            _matches = [(code, val) for code, val in identifiers.items()
                        if self.cid in val[1]]
            if len(_matches) > 1:
                # Rare, but multiple codes may end up with the same identifier
                # See CID 12300 for example
                codes = ", ".join([f"'{v[0]}'" for v in _matches])
                raise AttributeError(
                    f"'{name}' has multiple code matches in CID {self.cid}: "
                    f"{codes}")

            code, val = _matches[0]

        return Code(value=code, meaning=val[0], scheme_designator=scheme)
 def test_cid630(self):
     assert codes.cid630.LidocainePrilocaine == Code(
         value="346553009",
         scheme_designator="SCT",
         meaning="Lidocaine + Prilocaine",
     )
 def test_cid622(self):
     assert codes.cid622.NeuromuscularBlockingNMBNonDepolarizing == Code(
         value="372790002",
         scheme_designator="SCT",
         meaning="NeuroMuscular Blocking (NMB) - non depolarizing",
     )
 def test_cid612(self):
     assert codes.cid612.MonitoredAnesthesiaCareMAC == Code(
         value="398239001",
         scheme_designator="SCT",
         meaning="Monitored Anesthesia Care (MAC)",
     )
 def test_dcm_1(self):
     assert codes.DCM.Modality == Code(
         value="121139", scheme_designator="DCM", meaning="Modality"
     )
 def test_cid610(self):
     assert codes.cid610.ReverseOsmosisPurifiedHclAcidifiedWater == Code(
         value="127291",
         scheme_designator="DCM",
         meaning="Reverse osmosis purified, HCl acidified water",
     )
 def test_contained(self):
     c = Code("24028007", "SCT", "Right")
     assert c in codes.cid244
 def test_cid300(self):
     assert codes.cid300.NickelCobaltChromium == Code(
         value="261249004",
         scheme_designator="SCT",
         meaning="Nickel cobalt chromium",
     )
 def test_cid301(self):
     assert codes.cid301.mgcm3 == Code(
         value="mg/cm3", scheme_designator="UCUM", meaning="mg/cm^3"
     )
 def test_cid3111(self):
     assert codes.cid3111.Tc99mTetrofosmin == Code(
         value="404707004",
         scheme_designator="SCT",
         meaning="Tc-99m tetrofosmin",
     )
 def test_cid250(self):
     assert codes.cid250.Positive == Code(
         value="10828004", scheme_designator="SCT", meaning="Positive"
     )
 def test_sct_1(self):
     assert codes.SCT._1SigmaLowerValueOfPopulation == Code(
         value="371919006",
         scheme_designator="SCT",
         meaning="1 Sigma Lower Value of Populuation",
     )
 def test_dcm_3(self):
     assert codes.DCM.ImagingStartDatetime == Code(
         value="122712",
         scheme_designator="DCM",
         meaning="Imaging Start DateTime",
     )
 def test_not_contained(self):
     c = Code("130290", "DCM", "Median")
     assert c not in codes.cid244
 def test_cid643(self):
     assert codes.cid643._6Hydroxydopamine == Code(
         value="4624",
         scheme_designator="PUBCHEM_CID",
         meaning="6-Hydroxydopamine",
     )
 def test_cid402(self):
     assert codes.cid402.DestinationRoleID == Code(
         value="110152",
         scheme_designator="DCM",
         meaning="Destination Role ID",
     )
 def test_cid3107(self):
     assert codes.cid3107._13Nitrogen == Code(
         value="21576001", scheme_designator="SCT", meaning="^13^Nitrogen"
     )
 def test_cid405(self):
     assert codes.cid405.MultiMediaCard == Code(
         value="110035", scheme_designator="DCM", meaning="Multi-media Card"
     )
 def test_sct_2(self):
     assert codes.SCT.FindingSite == Code(
         value="363698007", scheme_designator="SCT", meaning="Finding Site"
     )
 def test_cid3335(self):
     assert codes.cid3335.PWaveSecondDeflectionInPWave == Code(
         value="10:320",
         scheme_designator="MDC",
         meaning="P' wave (second deflection in P wave)",
     )