Skip to content

Modality

pyorthanc.Modality

Wrapper around Orthanc API when dealing with a modality.

Source code in pyorthanc/_modality.py
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
class Modality:
    """Wrapper around Orthanc API when dealing with a modality."""

    def __init__(self, client: Orthanc, modality: str) -> None:
        """Constructor

        Parameters
        ----------
        client
            Orthanc object.
        modality
            Remote modality.
        """
        client = util.ensure_non_raw_response(client)

        self.client = client
        self.modality = modality

    def echo(self) -> bool:
        """C-Echo to modality

        Returns
        -------
        bool
            True if C-Echo succeeded.
        """
        try:
            self.client.post_modalities_id_echo(self.modality)
            return True

        except httpx.HTTPError:
            return False

    def get(self, level: str, resources: Union[List[Dict[str, Any]], Dict[str, Any]]) -> Dict:
        """C-GET

        C-Move SCU: Send all the results to another modality whose AET is in the body

        Parameters
        ----------
        level
            Level of the query ['Patient', 'Study', 'Series', 'Instance']
        resources
            Dict or list of dict of DICOM tags that identify data to retrieve,
            e.g. {'StudyInstanceUID': '1.3.6.1.4.1.22213.2.6291.2.1'}

        Returns
        -------
        Dict
            Orthanc Response (probably a Dictionary)

        Examples
        --------
        >>> modality = Modality(Orthanc('http://localhost:8042'), 'modality')
        >>> query_id = modality.get(
        ...     data={
        ...         'Level': 'Study',
        ...         'Resources': {'StudyInstanceUID': '1.3.6.1.4.1.22213.2.6291.2.1'}
        ...     }
        ... )

        """
        _validate_level(level)
        if isinstance(resources, dict):
            resources = [resources]

        return dict(self.client.post_modalities_id_get(self.modality, json={
            'Level': level,
            'Resources': resources
        }))

    def find(self, data: Dict) -> Dict:
        """C-Find (Querying with data)

        Parameters
        ----------
        data
            Dictionary to send in the body of request.

        Returns
        -------
        Dict
            Returns a dictionary with the query ID and corresponding matches (i.e. answers) to the request
            {'ID': '<query_id>', 'answers': [{first match metadata}, {second math metadata}, ...]}

        Examples
        -------
        >>> data = {'Level': 'Study',
        ...         'Query': {
        ...             'PatientID':'03HD*',
        ...             'StudyDescription':'*Chest*',
        ...             'PatientName':''
        ...         }
        ... }

        >>> modality = Modality(
        ...     client=Orthanc('http://localhost:8042'),
        ...     modality='sample'
        ... )

        >>> response = modality.find(data)
        >>> print(response['ID'], response['answers'])
        """
        query_id = self.client.post_modalities_id_query(self.modality, json=data)['ID']
        answers = self.get_query_answers(query_id)

        return {'ID': query_id, 'answers': answers}

    query = find  # Alias

    def move(self, query_identifier: str, cmove_data: Dict = None) -> Dict:
        """C-Move query results to another modality

        C-Move SCU: Send all the results to another modality whose AET is in the body

        Parameters
        ----------
        query_identifier
            Query identifier.
        cmove_data
            Ex. {'TargetAet': 'target_modality_name', "Synchronous": False}

        Returns
        -------
        Dict
            Orthanc Response (probably a Dictionary)

        Examples
        --------
        >>> modality = Modality(Orthanc('http://localhost:8042'), 'modality')
        >>> query_id = modality.query(
        ...     data={'Level': 'Series',
        ...           'Query': {'PatientID': '',
        ...                     'Modality':'SR'}})

        >>> modality.move(
        ...     query_identifier=query_id['ID'],
        ...     cmove_data={'TargetAet': 'TARGETAET'}
        ... )

        """
        return dict(self.client.post_queries_id_retrieve(query_identifier, json=cmove_data))

    def store(self, instance_or_series_id: str) -> Dict:
        """Store series or instance to modality.

        Parameters
        ----------
        instance_or_series_id
            Instance or Series Orthanc identifier.

        Returns
        -------
        Dict
            Information related to the C-Store operation.
        """
        return dict(self.client.post_modalities_id_store(
            self.modality,
            json=instance_or_series_id
        ))

    def get_query_answers(self, query_id: str, simplify: bool = True, short: bool = False) -> List[Dict]:
        """"""
        params = self._make_response_format_params(simplify=simplify, short=short)

        answers = []
        for answer_id in self.client.get_queries_id_answers(query_id):
            answer_content = self.client.get_queries_id_answers_index_content(query_id, answer_id, params)
            answers.append(answer_content)

        return answers

    def _make_response_format_params(self, simplify: bool, short: bool) -> Dict:
        if simplify and not short:
            params = {'simplify': True}
        elif short and not simplify:
            params = {'short': True}
        elif simplify and short:
            raise ValueError("simplify and short can't be both True.")
        else:
            params = {}

        return params

client = client instance-attribute

modality = modality instance-attribute

query = find class-attribute instance-attribute

__init__(client, modality)

Constructor

Parameters:

Name Type Description Default
client Orthanc

Orthanc object.

required
modality str

Remote modality.

required
Source code in pyorthanc/_modality.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def __init__(self, client: Orthanc, modality: str) -> None:
    """Constructor

    Parameters
    ----------
    client
        Orthanc object.
    modality
        Remote modality.
    """
    client = util.ensure_non_raw_response(client)

    self.client = client
    self.modality = modality

_make_response_format_params(simplify, short)

Source code in pyorthanc/_modality.py
182
183
184
185
186
187
188
189
190
191
192
def _make_response_format_params(self, simplify: bool, short: bool) -> Dict:
    if simplify and not short:
        params = {'simplify': True}
    elif short and not simplify:
        params = {'short': True}
    elif simplify and short:
        raise ValueError("simplify and short can't be both True.")
    else:
        params = {}

    return params

echo()

C-Echo to modality

Returns:

Type Description
bool

True if C-Echo succeeded.

Source code in pyorthanc/_modality.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def echo(self) -> bool:
    """C-Echo to modality

    Returns
    -------
    bool
        True if C-Echo succeeded.
    """
    try:
        self.client.post_modalities_id_echo(self.modality)
        return True

    except httpx.HTTPError:
        return False

find(data)

C-Find (Querying with data)

Parameters:

Name Type Description Default
data Dict

Dictionary to send in the body of request.

required

Returns:

Type Description
Dict

Returns a dictionary with the query ID and corresponding matches (i.e. answers) to the request {'ID': '', 'answers': [{first match metadata}, {second math metadata}, ...]}

Examples:

>>> data = {'Level': 'Study',
...         'Query': {
...             'PatientID':'03HD*',
...             'StudyDescription':'*Chest*',
...             'PatientName':''
...         }
... }
>>> modality = Modality(
...     client=Orthanc('http://localhost:8042'),
...     modality='sample'
... )
>>> response = modality.find(data)
>>> print(response['ID'], response['answers'])
Source code in pyorthanc/_modality.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def find(self, data: Dict) -> Dict:
    """C-Find (Querying with data)

    Parameters
    ----------
    data
        Dictionary to send in the body of request.

    Returns
    -------
    Dict
        Returns a dictionary with the query ID and corresponding matches (i.e. answers) to the request
        {'ID': '<query_id>', 'answers': [{first match metadata}, {second math metadata}, ...]}

    Examples
    -------
    >>> data = {'Level': 'Study',
    ...         'Query': {
    ...             'PatientID':'03HD*',
    ...             'StudyDescription':'*Chest*',
    ...             'PatientName':''
    ...         }
    ... }

    >>> modality = Modality(
    ...     client=Orthanc('http://localhost:8042'),
    ...     modality='sample'
    ... )

    >>> response = modality.find(data)
    >>> print(response['ID'], response['answers'])
    """
    query_id = self.client.post_modalities_id_query(self.modality, json=data)['ID']
    answers = self.get_query_answers(query_id)

    return {'ID': query_id, 'answers': answers}

get(level, resources)

C-GET

C-Move SCU: Send all the results to another modality whose AET is in the body

Parameters:

Name Type Description Default
level str

Level of the query ['Patient', 'Study', 'Series', 'Instance']

required
resources Union[List[Dict[str, Any]], Dict[str, Any]]

Dict or list of dict of DICOM tags that identify data to retrieve, e.g. {'StudyInstanceUID': '1.3.6.1.4.1.22213.2.6291.2.1'}

required

Returns:

Type Description
Dict

Orthanc Response (probably a Dictionary)

Examples:

>>> modality = Modality(Orthanc('http://localhost:8042'), 'modality')
>>> query_id = modality.get(
...     data={
...         'Level': 'Study',
...         'Resources': {'StudyInstanceUID': '1.3.6.1.4.1.22213.2.6291.2.1'}
...     }
... )
Source code in pyorthanc/_modality.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def get(self, level: str, resources: Union[List[Dict[str, Any]], Dict[str, Any]]) -> Dict:
    """C-GET

    C-Move SCU: Send all the results to another modality whose AET is in the body

    Parameters
    ----------
    level
        Level of the query ['Patient', 'Study', 'Series', 'Instance']
    resources
        Dict or list of dict of DICOM tags that identify data to retrieve,
        e.g. {'StudyInstanceUID': '1.3.6.1.4.1.22213.2.6291.2.1'}

    Returns
    -------
    Dict
        Orthanc Response (probably a Dictionary)

    Examples
    --------
    >>> modality = Modality(Orthanc('http://localhost:8042'), 'modality')
    >>> query_id = modality.get(
    ...     data={
    ...         'Level': 'Study',
    ...         'Resources': {'StudyInstanceUID': '1.3.6.1.4.1.22213.2.6291.2.1'}
    ...     }
    ... )

    """
    _validate_level(level)
    if isinstance(resources, dict):
        resources = [resources]

    return dict(self.client.post_modalities_id_get(self.modality, json={
        'Level': level,
        'Resources': resources
    }))

get_query_answers(query_id, simplify=True, short=False)

Source code in pyorthanc/_modality.py
171
172
173
174
175
176
177
178
179
180
def get_query_answers(self, query_id: str, simplify: bool = True, short: bool = False) -> List[Dict]:
    """"""
    params = self._make_response_format_params(simplify=simplify, short=short)

    answers = []
    for answer_id in self.client.get_queries_id_answers(query_id):
        answer_content = self.client.get_queries_id_answers_index_content(query_id, answer_id, params)
        answers.append(answer_content)

    return answers

move(query_identifier, cmove_data=None)

C-Move query results to another modality

C-Move SCU: Send all the results to another modality whose AET is in the body

Parameters:

Name Type Description Default
query_identifier str

Query identifier.

required
cmove_data Dict

Ex. {'TargetAet': 'target_modality_name', "Synchronous": False}

None

Returns:

Type Description
Dict

Orthanc Response (probably a Dictionary)

Examples:

>>> modality = Modality(Orthanc('http://localhost:8042'), 'modality')
>>> query_id = modality.query(
...     data={'Level': 'Series',
...           'Query': {'PatientID': '',
...                     'Modality':'SR'}})
>>> modality.move(
...     query_identifier=query_id['ID'],
...     cmove_data={'TargetAet': 'TARGETAET'}
... )
Source code in pyorthanc/_modality.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
def move(self, query_identifier: str, cmove_data: Dict = None) -> Dict:
    """C-Move query results to another modality

    C-Move SCU: Send all the results to another modality whose AET is in the body

    Parameters
    ----------
    query_identifier
        Query identifier.
    cmove_data
        Ex. {'TargetAet': 'target_modality_name', "Synchronous": False}

    Returns
    -------
    Dict
        Orthanc Response (probably a Dictionary)

    Examples
    --------
    >>> modality = Modality(Orthanc('http://localhost:8042'), 'modality')
    >>> query_id = modality.query(
    ...     data={'Level': 'Series',
    ...           'Query': {'PatientID': '',
    ...                     'Modality':'SR'}})

    >>> modality.move(
    ...     query_identifier=query_id['ID'],
    ...     cmove_data={'TargetAet': 'TARGETAET'}
    ... )

    """
    return dict(self.client.post_queries_id_retrieve(query_identifier, json=cmove_data))

store(instance_or_series_id)

Store series or instance to modality.

Parameters:

Name Type Description Default
instance_or_series_id str

Instance or Series Orthanc identifier.

required

Returns:

Type Description
Dict

Information related to the C-Store operation.

Source code in pyorthanc/_modality.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def store(self, instance_or_series_id: str) -> Dict:
    """Store series or instance to modality.

    Parameters
    ----------
    instance_or_series_id
        Instance or Series Orthanc identifier.

    Returns
    -------
    Dict
        Information related to the C-Store operation.
    """
    return dict(self.client.post_modalities_id_store(
        self.modality,
        json=instance_or_series_id
    ))

RemoteModality

RemoteModality is an alias for Modality

RemoteModality = Modality