-
Notifications
You must be signed in to change notification settings - Fork 13
/
clinicaldata.py
1252 lines (1006 loc) · 42.8 KB
/
clinicaldata.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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
from rwslib.builders.common import ODMElement, TransactionalElement, bool_to_yes_no, dt_to_iso8601, VALID_ID_CHARS
from rwslib.builders.modm import LastUpdateMixin, MilestoneMixin
from rwslib.builders.metadata import MeasurementUnitRef
from rwslib.builders.constants import ProtocolDeviationStatus, QueryStatusType
from collections import OrderedDict
from datetime import datetime
import re
class ClinicalData(ODMElement, LastUpdateMixin):
"""Models the ODM ClinicalData object"""
def __init__(self, projectname, environment, metadata_version_oid="1",
annotations=None):
"""
:param projectname: Name of Project in Medidata Rave
:param environment: Rave Study Enviroment
:param metadata_version_oid: MetadataVersion OID
"""
super(ClinicalData, self).__init__()
self.projectname = projectname
self.environment = environment
self.metadata_version_oid = metadata_version_oid
#: collection of :class:`SubjectData` for the ClinicalData Element
self.subject_data = []
self.annotations = annotations
def build(self, builder):
"""Build XML by appending to builder"""
params = dict(MetaDataVersionOID=str(self.metadata_version_oid),
StudyOID="%s (%s)" % (self.projectname, self.environment,),
)
# mixins
self.mixin_params(params)
builder.start("ClinicalData", params)
# Ask children
if self.subject_data:
for subject in self.subject_data:
subject.build(builder)
# Add the Annotations
if self.annotations is not None:
self.annotations.build(builder)
builder.end("ClinicalData")
def __lshift__(self, other):
"""Override << operator"""
if not isinstance(other, (SubjectData, Annotations)):
raise ValueError("ClinicalData object can only receive SubjectData or Annotations object")
self.set_list_attribute(other, SubjectData, 'subject_data')
self.set_single_attribute(other, Annotations, 'annotations')
return other
class SubjectData(TransactionalElement, LastUpdateMixin, MilestoneMixin):
"""Models the ODM SubjectData and ODM SiteRef objects"""
ALLOWED_TRANSACTION_TYPES = ['Insert', 'Update', 'Upsert']
def __init__(self, site_location_oid, subject_key, subject_key_type="SubjectName", transaction_type="Update"):
"""
:param str site_location_oid: :class:`SiteLocation` OID
:param str subject_key: Value for SubjectKey
:param str subject_key_type: Specifier as to the type of SubjectKey (either **SubjectName** or **SubjectUUID**)
:param str transaction_type: Transaction Type for Data (one of **Insert**, **Update**, **Upsert**)
"""
super(self.__class__, self).__init__(transaction_type)
self.sitelocationoid = site_location_oid
self.subject_key = subject_key
self.subject_key_type = subject_key_type
#: collection of :class:`StudyEventData`
self.study_events = []
#: collection of :class:`Annotation`
self.annotations = []
#: :class:`AuditRecord` for SubjectData - *Not Supported By Rave*
self.audit_record = None
#: :class:`Signature` for SubjectData
self.signature = None
#: :class:`SiteRef`
self.siteref = None
def build(self, builder):
"""Build XML by appending to builder"""
params = dict(SubjectKey=self.subject_key)
params['mdsol:SubjectKeyType'] = self.subject_key_type
if self.transaction_type is not None:
params["TransactionType"] = self.transaction_type
# mixins
self.mixin()
self.mixin_params(params)
builder.start("SubjectData", params)
# Ask children
if self.audit_record is not None:
self.audit_record.build(builder)
if self.siteref:
self.siteref.build(builder)
else:
builder.start("SiteRef", {'LocationOID': self.sitelocationoid})
builder.end("SiteRef")
for event in self.study_events:
event.build(builder)
if self.signature is not None:
self.signature.build(builder)
for annotation in self.annotations:
annotation.build(builder)
builder.end("SubjectData")
def __lshift__(self, other):
"""Override << operator"""
if not isinstance(other, (StudyEventData, AuditRecord, Annotation, Signature, SiteRef)):
raise ValueError("SubjectData object can only receive StudyEventData, AuditRecord, "
"Annotation or Signature object")
self.set_list_attribute(other, Annotation, 'annotations')
self.set_list_attribute(other, StudyEventData, 'study_events')
self.set_single_attribute(other, AuditRecord, 'audit_record')
self.set_single_attribute(other, Signature, 'signature')
self.set_single_attribute(other, SiteRef, 'siteref')
return other
class StudyEventData(TransactionalElement, LastUpdateMixin, MilestoneMixin):
"""Models the ODM StudyEventData object"""
ALLOWED_TRANSACTION_TYPES = ['Insert', 'Update', 'Remove', 'Context']
def __init__(self, study_event_oid, transaction_type="Update", study_event_repeat_key=None):
"""
:param str study_event_oid: :class:`StudyEvent` OID
:param str transaction_type: Transaction Type for Data (one of **Insert**, **Update**, *Remove*, **Context**)
:param int study_event_repeat_key: :attr:`StudyEventRepeatKey` for StudyEventData
"""
super(self.__class__, self).__init__(transaction_type)
self.study_event_oid = study_event_oid
self.study_event_repeat_key = study_event_repeat_key
#: :class:`FormData` part of Study Event Data
self.forms = []
#: :class:`Annotation` for Study Event Data - *Not Supported by Rave*
self.annotations = []
#: :class:`Signature` for Study Event Data
self.signature = None
def build(self, builder):
"""Build XML by appending to builder
:Example:
<StudyEventData StudyEventOID="SCREENING" StudyEventRepeatKey="1" TransactionType="Update">
"""
params = dict(StudyEventOID=self.study_event_oid)
if self.transaction_type is not None:
params["TransactionType"] = self.transaction_type
if self.study_event_repeat_key is not None:
params["StudyEventRepeatKey"] = str(self.study_event_repeat_key)
# mixins
self.mixin()
self.mixin_params(params)
builder.start("StudyEventData", params)
# Ask children
for form in self.forms:
form.build(builder)
if self.signature is not None:
self.signature.build(builder)
for annotation in self.annotations:
annotation.build(builder)
builder.end("StudyEventData")
def __lshift__(self, other):
"""Override << operator"""
if not isinstance(other, (FormData, Annotation, Signature)):
raise ValueError("StudyEventData object can only receive FormData, Signature or Annotation objects")
self.set_list_attribute(other, FormData, 'forms')
self.set_single_attribute(other, Signature, 'signature')
self.set_list_attribute(other, Annotation, 'annotations')
return other
class FormData(TransactionalElement, LastUpdateMixin, MilestoneMixin):
"""Models the ODM FormData object"""
ALLOWED_TRANSACTION_TYPES = ['Insert', 'Update']
def __init__(self, formoid, transaction_type=None, form_repeat_key=None):
"""
:param str formoid: :class:`FormDef` OID
:param str transaction_type: Transaction Type for Data (one of **Insert**, **Update**)
:param str form_repeat_key: Repeat Key for FormData
"""
super(FormData, self).__init__(transaction_type)
self.formoid = formoid
self.form_repeat_key = form_repeat_key
self.itemgroups = []
#: :class:`Signature` for FormData
self.signature = None # type: Signature
#: Collection of :class:`Annotation` for FormData - *Not supported by Rave*
self.annotations = [] # type: list(Annotation)
def build(self, builder):
"""Build XML by appending to builder
:Example:
<FormData FormOID="MH" TransactionType="Update">
"""
params = dict(FormOID=self.formoid)
if self.transaction_type is not None:
params["TransactionType"] = self.transaction_type
if self.form_repeat_key is not None:
params["FormRepeatKey"] = str(self.form_repeat_key)
# mixins
self.mixin()
self.mixin_params(params)
builder.start("FormData", params)
# Ask children
for itemgroup in self.itemgroups:
itemgroup.build(builder, self.formoid)
if self.signature is not None:
self.signature.build(builder)
for annotation in self.annotations:
annotation.build(builder)
builder.end("FormData")
def __lshift__(self, other):
"""Override << operator"""
if not isinstance(other, (Signature, ItemGroupData, Annotation)):
raise ValueError(
"FormData object can only receive ItemGroupData, Signature or Annotation objects (not '{}')".format(
other))
self.set_list_attribute(other, ItemGroupData, 'itemgroups')
self.set_list_attribute(other, Annotation, 'annotations')
self.set_single_attribute(other, Signature, 'signature')
return other
class ItemGroupData(TransactionalElement, LastUpdateMixin, MilestoneMixin):
"""
Models the ODM ItemGroupData object.
.. note:: No name for the ItemGroupData element is required. This is built automatically by the form.
"""
ALLOWED_TRANSACTION_TYPES = ['Insert', 'Update', 'Upsert', 'Context']
def __init__(self, itemgroupoid=None, transaction_type=None, item_group_repeat_key=None,
whole_item_group=False, annotations=None):
"""
:param str transaction_type: TransactionType for the ItemGroupData
:param int item_group_repeat_key: RepeatKey for the ItemGroupData
:param bool whole_item_group: Is this the entire ItemGroupData, or just parts? - *Rave specific attribute*
:param annotations: Annotation for the ItemGroup - *Not supported by Rave*
:type annotations: list(Annotation) or Annotation
"""
super(self.__class__, self).__init__(transaction_type)
self.item_group_repeat_key = item_group_repeat_key
self.whole_item_group = whole_item_group
self.items = OrderedDict()
self.annotations = []
if annotations:
# Add the annotations
if isinstance(annotations, Annotation):
self << annotations
elif isinstance(annotations, list):
for annotation in annotations:
self << annotation
#: :class:`Signature` for ItemGroupData
self.signature = None
self.itemgroupoid = itemgroupoid
def build(self, builder, formname=None):
"""Build XML by appending to builder"""
params = dict(ItemGroupOID=formname if formname else self.itemgroupoid)
if self.transaction_type is not None:
params["TransactionType"] = self.transaction_type
if self.item_group_repeat_key is not None:
params["ItemGroupRepeatKey"] = str(
self.item_group_repeat_key) # may be @context for transaction type upsert or context
params["mdsol:Submission"] = "WholeItemGroup" if self.whole_item_group else "SpecifiedItemsOnly"
# mixins
self.mixin()
self.mixin_params(params)
builder.start("ItemGroupData", params)
# Ask children
for item in self.items.values():
item.build(builder)
# Add annotations
for annotation in self.annotations:
annotation.build(builder)
# Add the signature if it exists
if self.signature is not None:
self.signature.build(builder)
builder.end("ItemGroupData")
def __lshift__(self, other):
"""Override << operator"""
if not isinstance(other, (ItemData, Annotation, Signature)):
raise ValueError("ItemGroupData object can only receive ItemData, Signature or Annotation objects")
self.set_list_attribute(other, Annotation, 'annotations')
self.set_single_attribute(other, Signature, 'signature')
if isinstance(other, ItemData):
if other.itemoid in self.items:
raise ValueError("ItemGroupData object with that itemoid is already in the ItemGroupData object")
self.items[other.itemoid] = other
return other
class ItemData(TransactionalElement, LastUpdateMixin, MilestoneMixin):
"""Models the ODM ItemData object"""
ALLOWED_TRANSACTION_TYPES = ['Insert', 'Update', 'Upsert', 'Context', 'Remove']
def __init__(self, itemoid, value, specify_value=None, transaction_type=None, lock=None, freeze=None, verify=None):
"""
:param str itemoid: OID for the matching :class:`ItemDef`
:param str value: Value for the the ItemData
:param str specify_value: 'If other, specify' value - *Rave specific attribute*
:param str transaction_type: Transaction type for the data
:param bool lock: Lock the DataPoint? - *Rave specific attribute*
:param bool freeze: Freeze the DataPoint? - *Rave specific attribute*
:param bool verify: Verify the DataPoint? - *Rave specific attribute*
"""
super(self.__class__, self).__init__(transaction_type)
self.itemoid = itemoid
self.value = value
self.specify_value = specify_value
self.lock = lock
self.freeze = freeze
self.verify = verify
#: the corresponding :class:`AuditRecord` for the DataPoint
self.audit_record = None
#: the list of :class:`MdsolQuery` on the DataPoint - *Rave Specific Attribute*
self.queries = []
#: the list of :class:`Annotation` on the DataPoint - *Not supported by Rave*
self.annotations = []
#: the corresponding :class:`MeasurementUnitRef` for the DataPoint
self.measurement_unit_ref = None
#: the list of :class:`MdsolProtocolDeviation` references on the DataPoint - *Rave Specific Attribute*
self.deviations = []
def build(self, builder):
"""
Build XML by appending to builder
"""
params = dict(ItemOID=self.itemoid)
if self.transaction_type is not None:
params["TransactionType"] = self.transaction_type
if self.value in [None, '']:
params['IsNull'] = 'Yes'
else:
params['Value'] = str(self.value)
if self.specify_value is not None:
params['mdsol:SpecifyValue'] = self.specify_value
if self.lock is not None:
params['mdsol:Lock'] = bool_to_yes_no(self.lock)
if self.freeze is not None:
params['mdsol:Freeze'] = bool_to_yes_no(self.freeze)
if self.verify is not None:
params['mdsol:Verify'] = bool_to_yes_no(self.verify)
# mixins
self.mixin()
self.mixin_params(params)
builder.start("ItemData", params)
if self.audit_record is not None:
self.audit_record.build(builder)
# Measurement unit ref must be after audit record or RWS complains
if self.measurement_unit_ref is not None:
self.measurement_unit_ref.build(builder)
for query in self.queries: # type: MdsolQuery
query.build(builder)
for deviation in self.deviations: # type: MdsolProtocolDeviation
deviation.build(builder)
for annotation in self.annotations: # type: Annotation
annotation.build(builder)
builder.end("ItemData")
def __lshift__(self, other):
if not isinstance(other, (MeasurementUnitRef, AuditRecord, MdsolQuery, Annotation,
MdsolProtocolDeviation)):
raise ValueError("ItemData object can only receive MeasurementUnitRef, AuditRecord, Annotation,"
"MdsolProtocolDeviation or MdsolQuery objects")
self.set_single_attribute(other, MeasurementUnitRef, 'measurement_unit_ref')
self.set_single_attribute(other, AuditRecord, 'audit_record')
self.set_list_attribute(other, MdsolQuery, 'queries')
self.set_list_attribute(other, MdsolProtocolDeviation, 'deviations')
self.set_list_attribute(other, Annotation, 'annotations')
return other
class Signature(ODMElement):
"""
An electronic signature applies to a collection of clinical data.
This indicates that some user accepts legal responsibility for that data.
See 21 CFR Part 11.
The signature identifies the person signing, the location of signing,
the signature meaning (via the referenced SignatureDef),
the date and time of signing,
and (in the case of a digital signature) an encrypted hash of the included data.
"""
def __init__(self, signature_id=None, user_ref=None, location_ref=None, signature_ref=None, date_time_stamp=None):
#: Unique ID for Signature
"""
:param UserRef user_ref: :class:`UserRef` for :class:`User` signing Data
:param LocationRef location_ref: :class:`LocationRef` for :class:`Location` of signing
:param SignatureRef signature_ref: :class:`SignatureRef` for :class:`SignatureDef` providing signature meaning
:param date_time_stamp: :class:`DateTimeStamp` for the time of Signature
"""
self._id = None
if signature_id:
self.signature_id = signature_id
self.user_ref = user_ref
self.location_ref = location_ref
self.signature_ref = signature_ref
self.date_time_stamp = date_time_stamp
@property
def signature_id(self):
"""
The ID for the Signature
.. note:: If a Signature element is contained within a Signatures element, the ID attribute is required.
"""
return self._id
@signature_id.setter
def signature_id(self, id):
"""Set the ID for the Signature"""
self._id = id
def build(self, builder):
"""
Build XML by appending to builder
"""
params = {}
if self.signature_id is not None:
# If a Signature element is contained within a Signatures element, the ID attribute is required.
params['ID'] = self.signature_id
builder.start("Signature", params)
if self.user_ref is None:
raise ValueError("User Reference not set.")
self.user_ref.build(builder)
if self.location_ref is None:
raise ValueError("Location Reference not set.")
self.location_ref.build(builder)
if self.signature_ref is None:
raise ValueError("Signature Reference not set.")
self.signature_ref.build(builder)
if self.date_time_stamp is None:
raise ValueError("DateTime not set.")
self.date_time_stamp.build(builder)
builder.end("Signature")
def __lshift__(self, other):
if not isinstance(other, (UserRef, LocationRef, SignatureRef, DateTimeStamp,)):
raise ValueError("Signature cannot accept a child element of type %s" % other.__class__.__name__)
# Order is important, apparently
self.set_single_attribute(other, UserRef, 'user_ref')
self.set_single_attribute(other, LocationRef, 'location_ref')
self.set_single_attribute(other, SignatureRef, 'signature_ref')
self.set_single_attribute(other, DateTimeStamp, 'date_time_stamp')
return other
class Annotation(TransactionalElement):
"""
A general note about clinical data.
If an annotation has both a comment and flags, the flags should be related to the comment.
.. note:: Annotation is not supported by Medidata Rave
"""
ALLOWED_TRANSACTION_TYPES = ["Insert", "Update", "Remove", "Upsert", "Context"]
def __init__(self, annotation_id=None, seqnum=1,
flags=None, comment=None,
transaction_type=None):
"""
:param id: ID for this Annotation (required if contained within an Annotations element)
:type id: str or None
:param int seqnum: :attr:`SeqNum` for Annotation
:param flags: one or more :class:`Flag` for the Annotation
:type flags: Flag or list(Flag)
:param comment: one or more :class:`Comment` for the Annotation
:type comment: Comment
:param transaction_type: :attr:`TransactionType` for Annotation (one of **Insert**, **Update**, *Remove*, **Upsert**, **Context**)
"""
super(Annotation, self).__init__(transaction_type=transaction_type)
# initialise the flags collection
self.flags = []
if flags:
if isinstance(flags, (list, tuple)):
for flag in flags:
self << flag
elif isinstance(flags, Flag):
self << flags
else:
raise AttributeError("Flags attribute should be an iterable or Flag")
self._id = None
if annotation_id is not None:
self.annotation_id = annotation_id
self._seqnum = None
if seqnum is not None:
# validate the input
self.seqnum = seqnum
self.comment = comment
@property
def annotation_id(self):
"""
ID for annotation
.. note:: If an Annotation is contained with an Annotations element, the ID attribute is required.
"""
return self._id
@annotation_id.setter
def annotation_id(self, value):
"""Set ID for Annotation"""
if value in [None, ''] or str(value).strip() == '':
raise AttributeError("Invalid ID value supplied")
self._id = value
@property
def seqnum(self):
"""
SeqNum attribute (a small positive integer) uniquely identifies the annotation within its parent entity.
"""
return self._seqnum
@seqnum.setter
def seqnum(self, value):
"""
Set SeqNum for Annotation
:param value: SeqNum value
:type value: int
"""
if not re.match(r'\d+', str(value)) or value < 0:
raise AttributeError("Invalid SeqNum value supplied")
self._seqnum = value
def build(self, builder):
"""
Build XML by appending to builder
"""
params = {}
# Add in the transaction type
if self.transaction_type is not None:
params["TransactionType"] = self.transaction_type
if self.seqnum is None:
# SeqNum is not optional (and defaulted)
raise ValueError("SeqNum is not set.") # pragma: no cover
params["SeqNum"] = str(self.seqnum)
if self.annotation_id is not None:
# If an Annotation is contained with an Annotations element,
# the ID attribute is required.
params["ID"] = self.annotation_id
builder.start("Annotation", params)
if self.flags in (None, []):
raise ValueError('Flag is not set.')
# populate the flags
for flag in self.flags:
flag.build(builder)
# add the Comment, if it exists
if self.comment is not None:
self.comment.build(builder)
builder.end("Annotation")
def __lshift__(self, other):
if not isinstance(other, (Flag, Comment,)):
raise ValueError("Annotation cannot accept a child element of type %s" % other.__class__.__name__)
self.set_single_attribute(other, Comment, 'comment')
self.set_list_attribute(other, Flag, 'flags')
return other
class Annotations(ODMElement):
"""
Groups Annotation elements referenced by ItemData[TYPE] elements.
"""
def __init__(self, annotations=[]):
self.annotations = []
for annotation in annotations:
self << annotation
def build(self, builder):
"""
Build XML by appending to builder
"""
builder.start("Annotations")
# populate the flags
for annotation in self.annotations:
annotation.build(builder)
builder.end("Annotations")
def __lshift__(self, other):
if not isinstance(other, (Annotation,)):
raise ValueError("Annotations cannot accept a child element of type %s" % other.__class__.__name__)
self.set_list_attribute(other, Annotation, 'annotations')
return other
class Comment(ODMElement):
"""
A free-text (uninterpreted) comment about clinical data.
The comment may have come from the Sponsor or the clinical Site.
.. note:: Comment is not supported by Medidata Rave
"""
VALID_SPONSOR_OR_SITE_RESPONSES = ["Sponsor", "Site"]
def __init__(self, text=None, sponsor_or_site=None):
"""
:param str text: Text for Comment
:param str sponsor_or_site: Originator flag for Comment (either _Sponsor_ or _Site_)
"""
self._text = text
self._sponsor_or_site = sponsor_or_site
@property
def text(self):
"""Text content of Comment"""
return self._text
@text.setter
def text(self, value):
"""Set Text content for Comment (validation of input)"""
if value in (None, '') or value.strip() == "":
raise AttributeError("Empty text value is invalid.")
self._text = value
@property
def sponsor_or_site(self):
"""Originator of comment (either Sponsor or Site)"""
return self._sponsor_or_site
@sponsor_or_site.setter
def sponsor_or_site(self, value):
"""Set Originator with validation of input"""
if value not in Comment.VALID_SPONSOR_OR_SITE_RESPONSES:
raise AttributeError("%s sponsor_or_site value of %s is not valid" % (self.__class__.__name__,
value))
self._sponsor_or_site = value
def build(self, builder):
"""
Build XML by appending to builder
"""
if self.text is None:
raise ValueError("Text is not set.")
params = {}
if self.sponsor_or_site is not None:
params['SponsorOrSite'] = self.sponsor_or_site
builder.start("Comment", params)
builder.data(self.text)
builder.end("Comment")
class Flag(ODMElement):
"""
A machine-processable annotation on clinical data.
.. note:: Flag is not supported by Rave
"""
def __init__(self, flag_type=None, flag_value=None):
"""
:param FlagType flag_type: Type for Flag
:param FlagValue flag_value: Value for Flag
"""
self.flag_type = None
self.flag_value = None
if flag_type is not None:
self << flag_type
if flag_value is not None:
self << flag_value
def build(self, builder):
"""
Build XML by appending to builder
"""
builder.start("Flag", {})
if self.flag_type is not None:
self.flag_type.build(builder)
if self.flag_value is None:
raise ValueError('FlagValue is not set.')
self.flag_value.build(builder)
builder.end("Flag")
def __lshift__(self, other):
if not isinstance(other, (FlagType, FlagValue,)):
raise ValueError("Flag cannot accept a child element of type %s" % other.__class__.__name__)
# Order is important, apparently
self.set_single_attribute(other, FlagType, 'flag_type')
self.set_single_attribute(other, FlagValue, 'flag_value')
return other
class FlagType(ODMElement):
"""
The type of flag. This determines the purpose and semantics of the flag.
Different applications are expected to be interested in different types of flags.
The actual value must be a member of the referenced CodeList.
.. note:: FlagType is not supported by Rave
"""
def __init__(self, flag_type, codelist_oid=None):
"""
:param flag_type: Type for :class:`Flag`
"""
self.flag_type = flag_type
self._codelist_oid = None
if codelist_oid is not None:
self.codelist_oid = codelist_oid
@property
def codelist_oid(self):
"""Reference to the :class:`CodeList` for the FlagType"""
return self._codelist_oid
@codelist_oid.setter
def codelist_oid(self, value):
if value in (None, '') or value.strip() == "":
raise AttributeError("Empty CodeListOID value is invalid.")
self._codelist_oid = value
def build(self, builder):
"""
Build XML by appending to builder
"""
if self.codelist_oid is None:
raise ValueError("CodeListOID not set.")
builder.start("FlagType", dict(CodeListOID=self.codelist_oid))
builder.data(self.flag_type)
builder.end("FlagType")
class FlagValue(ODMElement):
"""
The value of the flag. The meaning of this value is typically dependent on the associated FlagType.
The actual value must be a member of the referenced CodeList.
.. note:: FlagValue is not supported by Rave
"""
def __init__(self, flag_value, codelist_oid=None):
"""
:param flag_value: Value for :class:`Flag`
"""
self.flag_value = flag_value
self._codelist_oid = None
if codelist_oid is not None:
self.codelist_oid = codelist_oid
@property
def codelist_oid(self):
"""Reference to the :class:`CodeList` for the FlagType"""
return self._codelist_oid
@codelist_oid.setter
def codelist_oid(self, value):
if value in (None, '') or value.strip() == "":
raise AttributeError("Empty CodeListOID value is invalid.")
self._codelist_oid = value
def build(self, builder):
"""
Build XML by appending to builder
"""
if self.codelist_oid is None:
raise ValueError("CodeListOID not set.")
builder.start("FlagValue", dict(CodeListOID=self.codelist_oid))
builder.data(self.flag_value)
builder.end("FlagValue")
class UserRef(ODMElement):
"""
Reference to a :class:`User`
"""
def __init__(self, oid):
"""
:param str oid: OID for referenced :class:`User`
"""
self.oid = oid
def build(self, builder):
"""
Build XML by appending to builder
"""
builder.start("UserRef", dict(UserOID=self.oid))
builder.end("UserRef")
class LocationRef(ODMElement):
"""
Reference to a :class:`Location`
"""
def __init__(self, oid):
"""
:param str oid: OID for referenced :class:`Location`
"""
self.oid = oid
def build(self, builder):
"""
Build XML by appending to builder
"""
builder.start("LocationRef", dict(LocationOID=str(self.oid)))
builder.end("LocationRef")
class SiteRef(ODMElement, LastUpdateMixin):
"""
Reference to a :class:`Location`
The default value is `SiteName`, and the value `SiteUUID` implies that the `LocationOID`
.. note:: The `mdsol:LocationOIDType` attribute should be used to indicate the type of `LocationOID`
"""
def __init__(self, oid):
"""
:param str oid: OID for referenced :class:`Location`
"""
self.oid = oid
def build(self, builder):
"""
Build XML by appending to builder
"""
params = dict(LocationOID=self.oid)
# mixins
self.mixin()
self.mixin_params(params)
builder.start("SiteRef", params)
builder.end("SiteRef")
class SignatureRef(ODMElement):
"""
Reference to a Signature
"""
def __init__(self, oid):
"""
:param str oid: OID for referenced :class:`Signature`
"""
self.oid = oid
def build(self, builder):
"""
Build XML by appending to builder
"""
builder.start("SignatureRef", dict(SignatureOID=self.oid))
builder.end("SignatureRef")
class ReasonForChange(ODMElement):
"""
A user-supplied reason for a data change.
"""
def __init__(self, reason):
"""
:param str reason: Supplied Reason for change
"""
self.reason = reason
def build(self, builder):
"""
Build XML by appending to builder
"""
builder.start("ReasonForChange", {})
builder.data(self.reason)
builder.end("ReasonForChange")
class DateTimeStamp(ODMElement):
"""
The date/time that the data entry, modification, or signature was performed.
This applies to the initial occurrence of the action, not to subsequent transfers between computer systems.
"""
def __init__(self, date_time):
#: specified DateTime for event
self.date_time = date_time
def build(self, builder):
"""
Build XML by appending to builder
"""
builder.start("DateTimeStamp", {})
if isinstance(self.date_time, datetime):
builder.data(dt_to_iso8601(self.date_time))
else:
builder.data(self.date_time)
builder.end("DateTimeStamp")
class SourceID(ODMElement):
"""
Information that identifies the source of the data within an originating system.
It is only meaningful within the context of that system.
"""
def __init__(self, source_id):
#: specified DateTime for event
self.source_id = source_id
def build(self, builder):
"""
Build XML by appending to builder
"""
builder.start("SourceID", {})
builder.data(self.source_id)
builder.end("SourceID")
class AuditRecord(ODMElement):
"""
An AuditRecord carries information pertaining to the creation, deletion, or modification of clinical data.
This information includes who performed that action, and where, when, and why that action was performed.
.. note:: AuditRecord is supported only by :class:`ItemData` in Rave
"""
EDIT_MONITORING = 'Monitoring'