def generalfix_VM1(ds, log):
    fixed = False
    elemsTobeCorrected = []
    for key, a in ds.items():
        a = ds[key]
        if key.is_private:
            continue
        try:
            dvr = dictionary_VM(key)
        except (BaseException):
            return fixed
        if dvr != '1':
            continue
        if a.VM <= 1:
            continue
        if (a.VR != 'LT' or a.VR != 'LO'):
            continue
        concat = '/'.join(a.value)
        ds[key] = DataElementX(key, a.VR, concat)
        fixed = True
        err = "<{}> {}".format(a.keyword, validate_vr.tag2str(a.tag))
        msg = ErrorInfo(
            "General Fix - Value Multiplicity for {} "\
                "is not allowed to be more than one".format(err),
            "fixed by concatenating all itmes into one {}".format(concat))
        log.append(msg.getWholeMessage())
        fixed = True
    return fixed
Exemple #2
0
 def test_dictionary_VM(self):
     """Test dictionary_VM"""
     assert dictionary_VM(0x00000000) == '1'
     assert dictionary_VM(0x00081163) == '2'
     assert dictionary_VM(0x0000901) == '1-n'
     assert dictionary_VM(0x00041141) == '1-8'
     assert dictionary_VM(0x00080008) == '2-n'
     assert dictionary_VM(0x00080309) == '1-3'
     assert dictionary_VM(0x00081162) == '3-3n'
Exemple #3
0
 def test_dictionary_VM(self):
     """Test dictionary_VM"""
     assert dictionary_VM(0x00000000) == '1'
     assert dictionary_VM(0x00081163) == '2'
     assert dictionary_VM(0x0000901) == '1-n'
     assert dictionary_VM(0x00041141) == '1-8'
     assert dictionary_VM(0x00080008) == '2-n'
     assert dictionary_VM(0x00080309) == '1-3'
     assert dictionary_VM(0x00081162) == '3-3n'
Exemple #4
0
def verifyVM(elem: DataElement,
             module: str,
             element: str,
             verbose: bool,
             log: list,
             multiplicityMin: uint32,
             multiplicityMax: uint32,
             specifiedSource=""):
    ttag = elem.tag
    current_vm = elem.VM
    vm = dictionary_VM(ttag)
    if multiplicityMax == 0 and multiplicityMin == 0:
        [dictmin, has_min_factor, dictmax, has_max_factor] = getVM_min_max(vm)
        source = MMsgDC("Dictionary")
    else:
        dictmin = multiplicityMin
        dictmax = multiplicityMax
        has_min_factor = False
        has_max_factor = False
        source = specifiedSource if len(specifiedSource) > 0 else MMsgDC(
            "ModuleDefinition")
    min_err = False
    max_err = False
    if has_min_factor:
        min_err = (current_vm % dictmin == 0)
    else:
        min_err = current_vm < dictmin
    if has_max_factor:
        max_err = (current_vm % dictmax == 0)
    else:
        max_err = current_vm > dictmin
    message = ""
    err = min_err and max_err
    if err:
        mssg = "{} {} vm is {} ({}".format(
            EMsgDC("BadAttributeValueMultiplicity"), vm, current_vm, dictmin)
        if (dictmin != dictmax or not has_max_factor or not has_min_factor):
            if not has_max_factor and dictmax == 0xFFFFFFFF:
                mssg += "-n"
            elif has_max_factor and dictmax > 1:
                mssg += "-{}n".format(dictmax)
            elif has_max_factor and dictmax == 1:
                mssg += "-n".format(dictmax)
            else:
                mssg += "-{}".format(dictmax)
        mssg += " {} {})".format(MMsgDC("RequiredBy"), source)
        if len(element) != 0:
            mssg += MMsgDC("Element") + "=<" + element + ">"
        if len(module) != 0:
            mssg += MMsgDC("Module") + "=<" + module + ">"
        log.append(mssg)
    return not err
Exemple #5
0
    def from_json(cls,
                  dataset_class,
                  tag,
                  vr,
                  value,
                  value_key,
                  bulk_data_uri_handler=None,
                  encodings=None):
        """Creates a DataElement from JSON.

        Parameters
        ----------
        dataset_class: Dataset derived class
            class used to create sequence items
        tag: pydicom.tag.Tag
            data element tag
        vr: str
            data element value representation
        value: list
            data element value(s)
        value_key: Union[str, None]
            key of the data element that contains the value
            (options: ``{"Value", "InlineBinary", "BulkDataURI"}``)
        bulk_data_uri_handler: Union[Callable, None]
            callable that accepts the "BulkDataURI" of the JSON representation
            of a data element and returns the actual value of that data element
            (retrieved via DICOMweb WADO-RS)

        Returns
        -------
        pydicom.dataelem.DataElement

        """
        # TODO: test wado-rs retrieve wrapper
        try:
            vm = dictionary_VM(tag)
        except KeyError:
            # Private tag
            vm = str(len(value))
        if value_key == 'Value':
            if not (isinstance(value, list)):
                fmt = '"{}" of data element "{}" must be a list.'
                raise TypeError(fmt.format(value_key, tag))
        elif value_key in {'InlineBinary', 'BulkDataURI'}:
            if isinstance(value, list):
                fmt = '"{}" of data element "{}" must be a {}.'
                expected_type = ('string' if value_key == 'BulkDataURI' else
                                 'bytes-like object')
                raise TypeError(fmt.format(value_key, tag, expected_type))
        if vr == 'SQ':
            elem_value = []
            for value_item in value:
                ds = dataset_class()
                if value_item:
                    for key, val in value_item.items():
                        if 'vr' not in val:
                            fmt = 'Data element "{}" must have key "vr".'
                            raise KeyError(fmt.format(tag))
                        unique_value_keys = tuple(
                            set(val.keys()) & set(jsonrep.JSON_VALUE_KEYS))
                        if len(unique_value_keys) == 0:
                            logger.debug(
                                'data element has neither key "{}".'.format(
                                    '" nor "'.join(jsonrep.JSON_VALUE_KEYS)))
                            elem = DataElement(tag=tag, value='', VR=vr)
                        else:
                            value_key = unique_value_keys[0]
                            elem = cls.from_json(dataset_class, key, val['vr'],
                                                 val[value_key], value_key)
                        ds.add(elem)
                elem_value.append(ds)
        elif vr == 'PN':
            # Special case, see DICOM Part 18 Annex F2.2
            elem_value = []
            for v in value:
                if not isinstance(v, dict):
                    # Some DICOMweb services get this wrong, so we
                    # workaround the issue and warn the user
                    # rather than raising an error.
                    logger.error(
                        'value of data element "{}" with VR Person Name (PN) '
                        'is not formatted correctly'.format(tag))
                    elem_value.append(v)
                else:
                    elem_value.extend(list(v.values()))
            if vm == '1':
                try:
                    elem_value = elem_value[0]
                except IndexError:
                    elem_value = ''
        else:
            if vm == '1':
                if value_key == 'InlineBinary':
                    elem_value = base64.b64decode(value)
                elif value_key == 'BulkDataURI':
                    if bulk_data_uri_handler is None:
                        logger.warning(
                            'no bulk data URI handler provided for retrieval '
                            'of value of data element "{}"'.format(tag))
                        elem_value = b''
                    else:
                        elem_value = bulk_data_uri_handler(value)
                else:
                    if value:
                        elem_value = value[0]
                    else:
                        elem_value = value
            else:
                elem_value = value
        if elem_value is None:
            logger.warning('missing value for data element "{}"'.format(tag))
            elem_value = ''

        elem_value = jsonrep.convert_to_python_number(elem_value, vr)

        try:
            if compat.in_py2 and vr == "PN":
                elem_value = PersonNameUnicode(elem_value, 'UTF8')
            return DataElement(tag=tag, value=elem_value, VR=vr)
        except Exception:
            raise ValueError(
                'Data element "{}" could not be loaded from JSON: {}'.format(
                    tag, elem_value))
def safe_get(dcm: FileDataset, tag: int) -> Optional[ParsedElementValue]:
    element = safe_get_(dcm, tag)
    VM: str = dictionary_VM(tag)
    return [] if element is None and VM != "1" else element