def test_explicit_vr_expected_implicit_used_strict(self):
     config.enforce_valid_values = True
     msg = ('Expected explicit VR, but found implicit VR - '
            'using implicit VR for reading')
     with pytest.raises(InvalidDicomError, match=msg):
         read_dataset(
             self.ds_implicit, is_implicit_VR=False, is_little_endian=True
         )
Exemple #2
0
 def test_explicit_vr_expected_implicit_used_strict(self):
     config.enforce_valid_values = True
     msg = ('Expected explicit VR, but found implicit VR - '
            'using implicit VR for reading')
     with pytest.raises(InvalidDicomError, match=msg):
         read_dataset(self.ds_implicit,
                      is_implicit_VR=False,
                      is_little_endian=True)
Exemple #3
0
def decode(bytestring, is_implicit_vr, is_little_endian):
    """Decode `bytestring` to a *pydicom* :class:`~pydicom.dataset.Dataset`.

    Parameters
    ----------
    byestring : io.BytesIO
        The encoded dataset in the DIMSE Message sent from the peer AE.
    is_implicit_vr : bool
        The dataset is encoded as implicit (``True``) or explicit VR
        (``False``).
    is_little_endian : bool
        The byte ordering of the encoded dataset, ``True`` for little endian,
        ``False`` for big endian.

    Returns
    -------
    pydicom.dataset.Dataset
        The decoded dataset.
    """
    ## Logging
    transfer_syntax = "Little Endian" if is_little_endian else "Big Endian"
    if is_implicit_vr:
        transfer_syntax += " Implicit"
    else:
        transfer_syntax += " Explicit"

    LOGGER.debug('pydicom.read_dataset() TransferSyntax="%s"', transfer_syntax)

    ## Decode the dataset
    # Rewind to the start of the stream
    bytestring.seek(0)
    return read_dataset(bytestring, is_implicit_vr, is_little_endian)
Exemple #4
0
def decode(b, is_implicit_VR, is_little_endian):
    """
    When sent a DIMSE Message from a peer AE, decode the data and convert
    it to a pydicom Dataset instance
    
    Parameters
    ----------
    b - io.BytesIO
        The DIMSE Message sent from the peer AE
    is_implicit_VR - bool
        Is implicit or explicit VR
    is_little_endian - bool
        The byte ordering, little or big endian
        
    Returns
    -------
    pydicom.Dataset
        The Message contents decoded into a Dataset
    """
    if is_little_endian:
        transfer_syntax = "Little Endian"
    else:
        transfer_syntax = "Big Endian"
    
    if is_implicit_VR:
        transfer_syntax += " Implicit"
    else:
        transfer_syntax += " Explicit"
    
    logger.debug('pydicom::read_dataset() TransferSyntax="%s"' %transfer_syntax)
    
    # Rewind to the start of the stream
    b.seek(0)
    return read_dataset(b, is_implicit_VR, is_little_endian)
Exemple #5
0
 def testBadSeparator(self):
     """Ensure that unchanged bad separator does raise an error..."""
     ds = filereader.read_dataset(self.bytesio,
                                  is_little_endian=True,
                                  is_implicit_VR=True)
     contour = ds.ROIContourSequence[0].ContourSequence[0]
     self.assertRaises(ValueError, getattr, contour, "ContourData")
Exemple #6
0
def decode(bytestring, is_implicit_vr, is_little_endian):
    """Decode `bytestring` to a pydicom Dataset.

    When sent a DIMSE Message from a peer AE, decode the data and convert
    it to a pydicom Dataset instance.

    Parameters
    ----------
    byestring : io.BytesIO
        The encoded dataset in the DIMSE Message sent from the peer AE.
    is_implicit_vr : bool
        The dataset is encoded as implicit or explicit VR.
    is_little_endian : bool
        The byte ordering of the encoded dataset, little or big endian.

    Returns
    -------
    pydicom.dataset.Dataset
        The decoded dataset.
    """
    ## Logging
    transfer_syntax = "Little Endian" if is_little_endian else "Big Endian"
    if is_implicit_vr:
        transfer_syntax += " Implicit"
    else:
        transfer_syntax += " Explicit"

    LOGGER.debug('pydicom.read_dataset() TransferSyntax="%s"', transfer_syntax)

    ## Decode the dataset
    # Rewind to the start of the stream
    bytestring.seek(0)
    return read_dataset(bytestring, is_implicit_vr, is_little_endian)
Exemple #7
0
 def testBadSeparator(self, enforce_valid_values):
     """Ensure that unchanged bad separator does raise an error..."""
     ds = filereader.read_dataset(self.bytesio, is_little_endian=True,
                                  is_implicit_VR=True)
     contour = ds.ROIContourSequence[0].ContourSequence[0]
     with pytest.raises(ValueError):
         getattr(contour, "ContourData")
Exemple #8
0
def split_dataset(path: Path) -> Tuple[Dataset, int]:
    """Return the file meta elements and the offset to the start of the dataset

    .. versionadded:: 2.0

    Parameters
    ----------
    path : pathlib.Path
        The path to a dataset written in the DICOM File Format.

    Returns
    -------
    pydicom.dataset.Dataset, int
        The File Meta elements as a Dataset instance and the byte offset to
        the start of the dataset itself. The File Meta dataset may be empty if
        no File Meta is present.
    """
    def _not_group_0002(tag: BaseTag, VR: Optional[str], length: int) -> bool:
        """Return True if the tag is not in group 0x0002, False otherwise."""
        return tag.group != 2

    with open(path, 'rb') as fp:
        read_preamble(fp, False)
        file_meta = read_dataset(fp,
                                 is_implicit_VR=False,
                                 is_little_endian=True,
                                 stop_when=_not_group_0002)
        return file_meta, fp.tell()
 def test_fail_decode_msg(self, vr_bytes, str_output):
     """Regression test for #791."""
     ds = read_dataset(
         BytesIO(b'\x08\x00\x01\x00' + vr_bytes +
                 b'\x00\x00\x00\x08\x00\x49'), False, True)
     msg = (r"Unknown Value Representation '{}' in tag \(0008, 0001\)".
            format(str_output))
     with pytest.raises(NotImplementedError, match=msg):
         print(ds)
Exemple #10
0
def decode(
    bytestring: BytesIO,
    is_implicit_vr: bool,
    is_little_endian: bool,
    deflated: bool = False,
) -> Dataset:
    """Decode `bytestring` to a *pydicom* :class:`~pydicom.dataset.Dataset`.

    .. versionchanged:: 1.5

        Added `deflated` keyword parameter

    Parameters
    ----------
    byestring : io.BytesIO
        The encoded dataset in the DIMSE Message sent from the peer AE.
    is_implicit_vr : bool
        The dataset is encoded as implicit (``True``) or explicit VR
        (``False``).
    is_little_endian : bool
        The byte ordering of the encoded dataset, ``True`` for little endian,
        ``False`` for big endian.
    deflated : bool, optional
        ``True`` if the dataset has been encoded using *Deflated Explicit VR
        Little Endian* transfer syntax (default ``False``).

    Returns
    -------
    pydicom.dataset.Dataset
        The decoded dataset.
    """
    transfer_syntax = ""
    if deflated:
        transfer_syntax = "Deflated "
        is_implicit_vr = False
        is_little_endian = True

    transfer_syntax += "Little Endian" if is_little_endian else "Big Endian"
    if is_implicit_vr:
        transfer_syntax += " Implicit"
    else:
        transfer_syntax += " Explicit"

    LOGGER.debug('pydicom.read_dataset() TransferSyntax="%s"', transfer_syntax)

    # Rewind to the start of the stream
    bytestring.seek(0)

    if deflated:
        # Decompress the dataset
        bytestring = BytesIO(
            zlib.decompress(bytestring.getvalue(), -zlib.MAX_WBITS))
        bytestring.seek(0)

    # Decode the dataset
    return read_dataset(bytestring, is_implicit_vr, is_little_endian)
Exemple #11
0
    def test_explicit_vr_expected_implicit_used(self):
        msg = ('Expected explicit VR, but found implicit VR - '
               'using implicit VR for reading')

        with pytest.warns(UserWarning, match=msg):
            ds = read_dataset(self.ds_implicit,
                              is_implicit_VR=False,
                              is_little_endian=True)
        assert 'ISO_IR 100' == ds.SpecificCharacterSet
        assert '20000101' == ds.StudyDate
    def testImplVRcomma(self):
        """util.fix_separator: Able to replace comma in Implicit VR dataset.."""
        fixer.fix_separator(b",", for_VRs=["DS", "IS"], process_unknown_VRs=False)
        ds = filereader.read_dataset(self.bytesio, is_little_endian=True, is_implicit_VR=True)
        expected = [valuerep.DSfloat(x) for x in ["2", "4", "8", "16"]]
        got = ds.ROIContourSequence[0].ContourSequence[0].ContourData
        config.reset_data_element_callback()

        msg = "Expected {0}, got {1}".format(expected, got)
        self.assertEqual(expected, got, msg)
Exemple #13
0
    def test_explicit_vr_expected_implicit_used(self):
        msg = ('Expected explicit VR, but found implicit VR - '
               'using implicit VR for reading')

        with pytest.warns(UserWarning, match=msg):
            ds = read_dataset(
                self.ds_implicit, is_implicit_VR=False, is_little_endian=True
            )
        assert ds.SpecificCharacterSet == 'ISO_IR 100'
        assert ds.StudyDate == '20000101'
Exemple #14
0
 def test_fail_decode_msg(self, vr_bytes, str_output):
     """Regression test for #791."""
     # start the dataset with a valid tag (SpecificCharacterSet),
     # as the first tag is used to check the VR
     ds = read_dataset(
         BytesIO(b'\x08\x00\x05\x00CS\x0a\x00ISO_IR 100'
                 b'\x08\x00\x06\x00' + vr_bytes +
                 b'\x00\x00\x00\x08\x00\x49'), False, True)
     msg = (r"Unknown Value Representation '{}' in tag \(0008, 0006\)".
            format(str_output))
     with pytest.raises(NotImplementedError, match=msg):
         print(ds)
Exemple #15
0
    def testImplVRcomma(self):
        """util.fix_separator:
           Able to replace comma in Implicit VR dataset.."""
        fixer.fix_separator(b",", for_VRs=["DS", "IS"],
                            process_unknown_VRs=False)
        ds = filereader.read_dataset(self.bytesio, is_little_endian=True,
                                     is_implicit_VR=True)
        expected = [valuerep.DSfloat(x) for x in ["2", "4", "8", "16"]]
        got = ds.ROIContourSequence[0].ContourSequence[0].ContourData
        config.reset_data_element_callback()

        assert expected == got
Exemple #16
0
    def test_null_value_for_fixed_vr(self):
        # Wipe first Contour Data, mark as length 0
        null_ds_bytes = self.ds_bytes.replace(b"\x08\x00\x00\x00",
                                              b"\x00\x00\x00\x00")
        contour_data = b"\x32\x2c\x34\x2c\x38\x2c\x31\x36"
        null_ds_bytes = null_ds_bytes.replace(contour_data, b"")
        fixer.fix_separator(b",",
                            for_VRs=["DS", "IS"],
                            process_unknown_VRs=False)
        ds = filereader.read_dataset(BytesIO(null_ds_bytes),
                                     is_little_endian=True,
                                     is_implicit_VR=True)

        assert ds.ROIContourSequence[0].ContourSequence[0].ContourData is None
Exemple #17
0
    def testImplVRcomma(self):
        """util.fix_separator:
           Able to replace comma in Implicit VR dataset.."""
        fixer.fix_separator(b",", for_VRs=["DS", "IS"],
                            process_unknown_VRs=False)
        ds = filereader.read_dataset(self.bytesio, is_little_endian=True,
                                     is_implicit_VR=True)
        got = ds.ROIContourSequence[0].ContourSequence[0].ContourData
        config.reset_data_element_callback()

        expected = [2., 4., 8., 16.]
        if have_numpy and config.use_DS_numpy:
            assert numpy.allclose(expected, got)
        else:
            assert expected == got
Exemple #18
0
    def test_process_unknown_vr(self):
        bad_vr_bytes = self.ds_bytes
        # tag (0900, 0010), length 4, value "1,2"
        bad_vr_bytes += (b"\x00\x09\x10\x00"
                         b"\x04\x00\x00\x00"
                         b"\x31\x2c\x32\x20")
        fixer.fix_separator(b",",
                            for_VRs=["DS", "IS"],
                            process_unknown_VRs=True)
        ds = filereader.read_dataset(BytesIO(bad_vr_bytes),
                                     is_little_endian=True,
                                     is_implicit_VR=True)
        got = ds.get((0x0900, 0x0010))
        assert got.value == b'1\\2 '

        # with process_unknown_VRs=False, unknown VR separator is not replaced
        fixer.fix_separator(b",",
                            for_VRs=["DS", "IS"],
                            process_unknown_VRs=False)
        ds = filereader.read_dataset(BytesIO(bad_vr_bytes),
                                     is_little_endian=True,
                                     is_implicit_VR=True)
        got = ds.get((0x0900, 0x0010))
        assert got.value == b'1,2 '
Exemple #19
0
 def test_fail_decode_msg(self, vr_bytes, str_output):
     """Regression test for #791."""
     ds = read_dataset(
         BytesIO(
             b'\x08\x00\x01\x00' +
             vr_bytes +
             b'\x00\x00\x00\x08\x00\x49'
         ),
         False, True
     )
     msg = (
         r"Unknown Value Representation '{}' in tag \(0008, 0001\)"
         .format(str_output)
     )
     with pytest.raises(NotImplementedError, match=msg):
         print(ds)
Exemple #20
0
    def test_write_explicit_vr_big_endian(self):
        """Test writing explicit big data for ambiguous elements."""
        # Create a dataset containing element with ambiguous VRs
        ref_ds = Dataset()
        ref_ds.PixelRepresentation = 1
        ref_ds.SmallestValidPixelValue = b'\x00\x01'  # Big endian 1

        fp = BytesIO()
        file_ds = FileDataset(fp, ref_ds)
        file_ds.is_implicit_VR = False
        file_ds.is_little_endian = False
        file_ds.save_as(fp)
        fp.seek(0)

        ds = read_dataset(fp, False, False)
        self.assertEqual(ds.SmallestValidPixelValue, 1)
        self.assertEqual(ds[0x00280104].VR, 'SS')
Exemple #21
0
    def test_write_explicit_vr_big_endian(self):
        """Test writing explicit big data for ambiguous elements."""
        # Create a dataset containing element with ambiguous VRs
        ref_ds = Dataset()
        ref_ds.PixelRepresentation = 1
        ref_ds.SmallestValidPixelValue = b'\x00\x01' # Big endian 1

        fp = BytesIO()
        file_ds = FileDataset(fp, ref_ds)
        file_ds.is_implicit_VR = False
        file_ds.is_little_endian = False
        file_ds.save_as(fp)
        fp.seek(0)

        ds = read_dataset(fp, False, False)
        self.assertEqual(ds.SmallestValidPixelValue, 1)
        self.assertEqual(ds[0x00280104].VR, 'SS')
Exemple #22
0
    def test_space_delimiter(self):
        # Change "32\64\128\196" to "32 64 128 196", keeping the trailing space
        existing = b"\x33\x32\x5c\x36\x34\x5c\x31\x32\x38\x5c\x31\x39\x36\x20"
        spaced = b"\x33\x32\x20\x36\x34\x20\x31\x32\x38\x20\x31\x39\x36\x20"
        space_ds_bytes = self.ds_bytes.replace(existing, spaced)
        fixer.fix_separator(b" ",
                            for_VRs=["DS", "IS"],
                            process_unknown_VRs=False)
        ds = filereader.read_dataset(BytesIO(space_ds_bytes),
                                     is_little_endian=True,
                                     is_implicit_VR=True)
        got = ds.ROIContourSequence[0].ContourSequence[1].ContourData

        expected = [32., 64., 128., 196.]
        if have_numpy and config.use_DS_numpy:
            assert numpy.allclose(expected, got)
        else:
            assert expected == got
Exemple #23
0
 def test_fail_decode_msg(self, vr_bytes, str_output):
     """Regression test for #791."""
     # start the dataset with a valid tag (SpecificCharacterSet),
     # as the first tag is used to check the VR
     ds = read_dataset(
         BytesIO(
             b'\x08\x00\x05\x00CS\x0a\x00ISO_IR 100'
             b'\x08\x00\x06\x00' +
             vr_bytes +
             b'\x00\x00\x00\x08\x00\x49'
         ),
         False, True
     )
     msg = (
         r"Unknown Value Representation '{}' in tag \(0008, 0006\)"
         .format(str_output)
     )
     with pytest.raises(NotImplementedError, match=msg):
         print(ds)
Exemple #24
0
 def testBadSeparator(self):
     """Ensure that unchanged bad separator does raise an error..........."""
     ds = filereader.read_dataset(self.bytesio, is_little_endian=True,
                                  is_implicit_VR=True)
     contour = ds.ROIContourSequence[0].ContourSequence[0]
     self.assertRaises(ValueError, getattr, contour, "ContourData")
Exemple #25
0
def decode(rawstr, is_implicit_VR, is_little_endian):
    s = StringIO.StringIO(rawstr)
    ds = read_dataset(s, is_implicit_VR, is_little_endian)
    return ds