-
Notifications
You must be signed in to change notification settings - Fork 71
/
delivery.py
392 lines (300 loc) · 12.4 KB
/
delivery.py
1
2
3
4
5
6
7
8
9
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# Copyright (C) 2018 Cancer Care Associates
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Uses Mosaiq SQL to extract patient delivery details.
"""
import functools
import struct
from pymedphys._imports import attr
from pymedphys._imports import numpy as np
from pymedphys._base.delivery import DeliveryBase
from pymedphys._utilities.transforms import convert_IEC_angle_to_bipolar
from .connect import execute_sql
from .constants import FIELD_TYPES
@functools.lru_cache()
def create_ois_delivery_details_class():
@attr.s
class OISDeliveryDetails:
"""A class containing patient information extracted from Mosaiq."""
patient_id = attr.ib()
field_id = attr.ib()
last_name = attr.ib()
first_name = attr.ib()
qa_mode = attr.ib()
field_type = attr.ib()
beam_completed = attr.ib()
return OISDeliveryDetails
class MultipleMosaiqEntries(ValueError):
"""Raise an exception when more than one disagreeing entry is found"""
class NoMosaiqEntries(ValueError):
"""Raise an exception when no entry is found"""
def get_field_type(cursor, field_id):
execute_string = """
SELECT
TxField.Type_Enum
FROM TxField
WHERE
TxField.FLD_ID = %(field_id)s
"""
parameters = {"field_id": field_id}
sql_result = execute_sql(cursor, execute_string, parameters)
return FIELD_TYPES[sql_result[0][0]]
def get_mosaiq_delivery_details(
cursor, machine, delivery_time, field_label, field_name, buffer=0
):
"""Identifies the patient details for a given delivery time.
Args:
Args:
cursor: A pymssql cursor pointing to the Mosaiq SQL server
machine: The name of the machine the delivery occured on
delivery_time: The time of the treatment delivery
field_label: The beam field label, called Field ID within Monaco
field_name: The beam field name, called Description within Monaco
Returns:
delivery_details: The identified delivery details
patient_id: User defined Mosaiq patient ID
field_id: Internal Mosaiq SQL field ID
last_name: Patient last name
first_name: Patient first name
qa_mode: Whether or not the delivery was in QA mode
field_type: What field type the delivery was
beam_completed: Whether or not this beam was the last in a sequence
"""
# TODO Need to update the logic here to search for previous treatments
# that were incomplete. Actually, this doesn't need to be in the indexing.
# Can solve this later on using multiple beams with one logfile ending in
# 'Terminated Fault'.
# TODO WasBeamComplete informs whether or not there were beams grouped
# together. If WasBeamComplete is false should actually search for
# subsequent beams until WasBeamComplete is true. This will help the case
# where multiple beams are MFSed into one delivery, resulting in multiple
# field ids and labels for a single logfile.
# TODO Convert all times to UTC so that timezone is not required within
# the API.
# https://docs.microsoft.com/en-us/sql/t-sql/queries/at-time-zone-transact-sql?view=sql-server-2017
execute_string = """
SELECT
Ident.IDA,
TxField.FLD_ID,
Patient.Last_Name,
Patient.First_Name,
Tracktreatment.WasQAMode,
TxField.Type_Enum,
Tracktreatment.WasBeamComplete
FROM TrackTreatment, Ident, Patient, TxField, Staff
WHERE
TrackTreatment.Pat_ID1 = Ident.Pat_ID1 AND
Patient.Pat_ID1 = Ident.Pat_ID1 AND
TrackTreatment.FLD_ID = TxField.FLD_ID AND
Staff.Staff_ID = TrackTreatment.Machine_ID_Staff_ID AND
REPLACE(Staff.Last_Name, ' ', '') = %(machine)s AND
TrackTreatment.Create_DtTm <= DATEADD(second, %(buffer)d, %(delivery_time)s) AND
TrackTreatment.Edit_DtTm >= DATEADD(second, -%(buffer)d, %(delivery_time)s) AND
TxField.Field_Label = %(field_label)s AND
TxField.Field_Name = %(field_name)s
"""
parameters = {
"buffer": buffer,
"machine": machine,
"delivery_time": delivery_time,
"field_label": field_label,
"field_name": field_name,
}
sql_result = execute_sql(cursor, execute_string, parameters)
if len(sql_result) > 1:
for result in sql_result[1::]:
if result != sql_result[0]:
if buffer != 0:
return get_mosaiq_delivery_details(
cursor,
machine,
delivery_time,
field_label,
field_name,
buffer=0,
)
raise MultipleMosaiqEntries("Disagreeing entries were found.")
if not sql_result:
raise NoMosaiqEntries(
"No Mosaiq entries were found for {}/{} at {}".format(
field_label, field_name, delivery_time
)
)
OISDeliveryDetails = create_ois_delivery_details_class()
delivery_details = OISDeliveryDetails(*sql_result[0])
delivery_details.field_type = FIELD_TYPES[delivery_details.field_type]
return delivery_details
def mosaiq_mlc_missing_byte_workaround(raw_bytes_list):
"""This function checks if there is an odd number of bytes in the mlc list
and appends a \\x00 if the byte number is odd.
It is uncertain whether or not this is the correct method to restore the
data.
"""
length = check_all_items_equal_length(raw_bytes_list, "mlc bytes")
if length % 2 == 1:
raw_bytes_list = append_x00_byte_to_all(raw_bytes_list)
check_all_items_equal_length(raw_bytes_list, "mlc bytes")
return raw_bytes_list
def append_x00_byte_to_all(raw_bytes_list):
appended_bytes_list = []
for item in raw_bytes_list:
bytes_as_list = list(item)
bytes_as_list.append(0)
appended_bytes_list.append(bytes(bytes_as_list))
return appended_bytes_list
def check_all_items_equal_length(items, name):
all_lengths = [len(item) for item in items]
length = list(set(all_lengths))
assert len(length) == 1, "All {} should be the same length".format(name)
return length[0]
def decode_msq_mlc(raw_bytes):
"""Convert MLCs from Mosaiq SQL byte format to cm floats.
"""
raw_bytes = mosaiq_mlc_missing_byte_workaround(raw_bytes)
length = check_all_items_equal_length(raw_bytes, "mlc bytes")
if length % 2 == 1:
raise ValueError(
"There should be an even number of bytes within an MLC record."
)
mlc_pos = (
np.array(
[
[
struct.unpack("<h", control_point[2 * i : 2 * i + 2])
for i in range(len(control_point) // 2)
]
for control_point in raw_bytes
]
)
/ 100
)
return mlc_pos
def collimation_to_bipolar_mm(mlc_a, mlc_b, coll_y1, coll_y2):
mlc1 = 10 * mlc_b[::-1, :]
mlc2 = -10 * mlc_a[::-1, :]
mlc = np.concatenate([mlc1[None, :, :], mlc2[None, :, :]], axis=0)
jaw1 = 10 * coll_y2
jaw2 = -10 * coll_y1
jaw = np.concatenate([jaw1[None, :], jaw2[None, :]], axis=0)
return mlc, jaw
def delivery_data_sql(cursor, field_id):
"""Get the treatment delivery data from Mosaiq given the SQL field_id
Args:
cursor: A pymssql cursor pointing to the Mosaiq SQL server
field_id: The Mosaiq SQL field ID
Returns:
txfield_results: The results from the TxField table.
txfieldpoint_results: The results from the TxFieldPoint table.
"""
txfield_results = execute_sql(
cursor,
"""
SELECT
TxField.Meterset
FROM TxField
WHERE
TxField.FLD_ID = %(field_id)s
""",
{"field_id": field_id},
)
txfieldpoint_results = np.array(
execute_sql(
cursor,
"""
SELECT
TxFieldPoint.[Index],
TxFieldPoint.A_Leaf_Set,
TxFieldPoint.B_Leaf_Set,
TxFieldPoint.Gantry_Ang,
TxFieldPoint.Coll_Ang,
TxFieldPoint.Coll_Y1,
TxFieldPoint.Coll_Y2
FROM TxFieldPoint
WHERE
TxFieldPoint.FLD_ID = %(field_id)s
""",
{"field_id": field_id},
)
)
return txfield_results, txfieldpoint_results
def fetch_and_verify_mosaiq_sql(cursor, field_id):
reference_results = delivery_data_sql(cursor, field_id)
test_results = delivery_data_sql(cursor, field_id)
agreement = False
while not agreement:
agreements = []
for ref, test in zip(reference_results, test_results):
agreements.append(np.all(ref == test))
agreement = np.all(agreements)
if not agreement:
print("Mosaiq sql query gave conflicting data.")
print("Trying again...")
reference_results = test_results
test_results = delivery_data_sql(cursor, field_id)
return test_results
class DeliveryMosaiq(DeliveryBase):
@classmethod
def from_mosaiq(cls, cursor, field_id):
mosaiq_delivery_data = cls._from_mosaiq_base(cursor, field_id)
reference_data = (
mosaiq_delivery_data.monitor_units,
mosaiq_delivery_data.mlc,
mosaiq_delivery_data.jaw,
)
delivery_data = cls._from_mosaiq_base(cursor, field_id)
test_data = (delivery_data.monitor_units, delivery_data.mlc, delivery_data.jaw)
agreement = False
while not agreement:
agreements = []
for ref, test in zip(reference_data, test_data):
agreements.append(np.all(ref == test))
agreement = np.all(agreements)
if not agreement:
print("Converted Mosaiq delivery data was conflicting.")
print(
"MU agreement: {}\nMLC agreement: {}\n"
"Jaw agreement: {}".format(*agreements)
)
print("Trying again...")
reference_data = test_data
delivery_data = cls._from_mosaiq_base(cursor, field_id)
test_data = (
delivery_data.monitor_units,
delivery_data.mlc,
delivery_data.jaw,
)
return delivery_data
@classmethod
def _from_mosaiq_base(cls, cursor, field_id):
txfield_results, txfieldpoint_results = fetch_and_verify_mosaiq_sql(
cursor, field_id
)
total_mu = np.array(txfield_results[0]).astype(float)
cumulative_percentage_mu = txfieldpoint_results[:, 0].astype(float)
if np.shape(cumulative_percentage_mu) == ():
mu_per_control_point = [0, total_mu]
else:
cumulative_mu = cumulative_percentage_mu * total_mu / 100
mu_per_control_point = np.concatenate([[0], np.diff(cumulative_mu)])
monitor_units = np.cumsum(mu_per_control_point).tolist()
mlc_a = np.squeeze(decode_msq_mlc(txfieldpoint_results[:, 1].astype(bytes))).T
mlc_b = np.squeeze(decode_msq_mlc(txfieldpoint_results[:, 2].astype(bytes))).T
msq_gantry_angle = txfieldpoint_results[:, 3].astype(float)
msq_collimator_angle = txfieldpoint_results[:, 4].astype(float)
coll_y1 = txfieldpoint_results[:, 5].astype(float)
coll_y2 = txfieldpoint_results[:, 6].astype(float)
mlc, jaw = collimation_to_bipolar_mm(mlc_a, mlc_b, coll_y1, coll_y2)
gantry = convert_IEC_angle_to_bipolar(msq_gantry_angle)
collimator = convert_IEC_angle_to_bipolar(msq_collimator_angle)
# TODO Tidy up this axis swap
mlc = np.swapaxes(mlc, 0, 2)
jaw = np.swapaxes(jaw, 0, 1)
mosaiq_delivery_data = cls(monitor_units, gantry, collimator, mlc, jaw)
return mosaiq_delivery_data