-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathqb_timeline.py
1395 lines (1187 loc) · 57.6 KB
/
qb_timeline.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
from collections import namedtuple
from datetime import MAXYEAR, datetime
from time import sleep
from dateutil.relativedelta import relativedelta
from flask import current_app
from redis.exceptions import ConnectionError
from sqlalchemy.types import Enum as SQLA_Enum
from werkzeug.exceptions import BadRequest
from ..audit import auditable_event
from ..cache import cache, TWO_HOURS
from ..database import db
from ..date_tools import FHIR_datetime, RelativeDelta
from ..factories.redis import create_redis
from ..set_tools import left_center_right
from ..timeout_lock import ADHERENCE_DATA_KEY, CacheModeration, TimeoutLock
from ..trace import trace
from .adherence_data import AdherenceData
from .overall_status import OverallStatus
from .qbd import QBD
from .questionnaire_bank import (
qbs_by_intervention,
qbs_by_rp,
trigger_date,
visit_name,
)
from .questionnaire_response import QNR_results, QuestionnaireResponse
from .research_protocol import ResearchProtocol
from .role import ROLE
from .user import User
from .user_consent import consent_withdrawal_dates
class QBT(db.Model):
"""Effectively a view, to simplify QB status lookups over time
A user has a number of QBT rows, at least one for each questionnaire
bank that has been due for the user, or will be in the future.
The following events would invalidate the respective rows (delete
said rows to invalidate):
- user's trigger date changed (consent or new procedure)
- user submits a QuestionnaireResponse
- the definition of a QB or an organization's research protocol
"""
__tablename__ = 'qb_timeline'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.ForeignKey(
'users.id', ondelete='cascade'), nullable=False, index=True)
at = db.Column(
db.DateTime, nullable=False, index=True,
doc="initial date time for state of row")
qb_id = db.Column(db.ForeignKey(
'questionnaire_banks.id', ondelete='cascade'), nullable=True)
qb_recur_id = db.Column(db.ForeignKey(
'recurs.id', ondelete='cascade'), nullable=True)
qb_iteration = db.Column(db.Integer, nullable=True)
status = db.Column(SQLA_Enum(OverallStatus), nullable=False, index=True)
research_study_id = db.Column(db.ForeignKey(
'research_studies.id', ondelete='cascade'),
nullable=False, index=True)
def qbd(self):
"""Generate and return a QBD instance from self data"""
return QBD(
relative_start=self.at, iteration=self.qb_iteration,
recur_id=self.qb_recur_id, qb_id=self.qb_id)
def __repr__(self):
"""simplifies debugging"""
return (
f"{visit_name(self.qbd())}({self.qb_id}:{self.qb_iteration})"
f" {self.status} @ {self.at}")
@staticmethod
def timeline_state(user_id):
"""Return an ordered list of user's QBT state for tracking changes"""
from .questionnaire_bank import QuestionnaireBank
name_map = QuestionnaireBank.name_map()
tl = QBT.query.filter(
QBT.user_id == user_id).with_entities(
QBT.at,
QBT.qb_id,
QBT.status,
QBT.qb_iteration).order_by(
QBT.at)
results = dict()
for i in tl:
qb = QuestionnaireBank.query.get(i.qb_id)
if qb is None:
continue
recur_id = qb.recurs[0].id if qb.recurs else None
vn = visit_name(QBD(
relative_start=None,
questionnaire_bank=qb,
iteration=i.qb_iteration,
recur_id=recur_id))
results[f"{i.at} {i.status}"] = [
vn, name_map[i.qb_id], i.qb_iteration]
return results
class AtOrderedList(list):
"""Specialize ``list`` to maintain insertion order and ``at`` attribute
When building up QBTs for a user, we need to maintain both order and
sort by the ``QBT.at`` attribute. As there are rows with identical ``at``
values, it can't simply be sorted by a field, as insertion order matters
in the case of a tie (as say the ``due`` status needs to precede a
``completed``, which does happen with paper entry).
As the build order matters, continue to add QBTs to the end of the list,
taking special care to insert those with earlier ``at`` values in
the correct place. Two or more identical ``at`` values should result
in the latest addition following preexisting.
"""
def append(self, value):
"""Maintain order by appending or inserting as needed
If the given value.at is > current_end.at, append to end.
Otherwise, walk backwards till the new can be inserted
so the list remains ordered by the 'at' attribute, with
new matching values following existing
"""
if not self.__len__():
return super(AtOrderedList, self).append(value)
# Expecting to build in order; common case new value
# lands at end.
if self[-1].at <= value.at:
return super(AtOrderedList, self).append(value)
# Otherwise, walk backwards till new value < existing
for i, e in reversed(list(enumerate(self))):
if i > 0:
# If not at start and previous is also greater
# than new, continue to walk backwards
if self[i-1].at > value.at:
continue
if e.at > value.at:
return self.insert(i, value)
raise ValueError("still here?")
def ordered_rp_qbs(rp_id, trigger_date):
"""Generator to yield ordered qbs by research protocol alone"""
baselines = qbs_by_rp(rp_id, 'baseline')
if len(baselines) > 1:
raise RuntimeError(
"Expect exactly one QB for baseline by rp {}".format(rp_id))
if len(baselines) == 0:
# typically only test scenarios - easy catch otherwise
return
baseline = baselines[0]
if baseline not in db.session:
baseline = db.session.merge(baseline, load=False)
start = baseline.calculated_start(trigger_date=trigger_date)
yield start
qbs_by_start = {}
recurring = qbs_by_rp(rp_id, 'recurring')
for qb in recurring:
if qb not in db.session:
qb = db.session.merge(qb, load=False)
for qbd in qb.recurring_starts(trigger_date):
qbs_by_start[qbd.relative_start] = qbd
# continue to yield in order
trace("found {} total recurring QBs".format(len(qbs_by_start)))
for start_date in sorted(qbs_by_start.keys()):
yield qbs_by_start[start_date]
def ordered_intervention_qbs(user, trigger_date):
"""Generator to yield ordered qbs by intervention"""
baselines = qbs_by_intervention(user, 'baseline')
if not baselines:
return
if len(baselines) > 1:
raise RuntimeError(
"{} has {} baselines by intervention (expected ONE)".format(
user, len(baselines)))
baseline = baselines[0]
if baseline not in db.session:
baseline = db.session.merge(baseline, load=False)
start = baseline.calculated_start(trigger_date=trigger_date)
yield start
qbs_by_start = {}
recurring = qbs_by_intervention(user, 'recurring')
for qb in recurring:
if qb not in db.session:
qb = db.session.merge(qb, load=False)
for qbd in qb.recurring_starts(trigger_date=trigger_date):
qbs_by_start[qbd.relative_start] = qbd
# continue to yield in order
for start_date in sorted(qbs_by_start.keys()):
yield qbs_by_start[start_date]
def indef_qbs_by_rp(rp_id, trigger_date):
"""Generator to yield ordered `indefinite` qbs by research protocol
At the moment, only expecting to yield one, but following generator
pattern to facilitate polymorphic code.
"""
indefinites = qbs_by_rp(rp_id, 'indefinite')
for indefinite in indefinites:
if indefinite not in db.session:
indefinite = db.session.merge(indefinite, load=False)
start = indefinite.calculated_start(trigger_date=trigger_date)
yield start
def indef_intervention_qbs(user, trigger_date):
"""Generator to yield indefinite qbs by intervention"""
indefinites = qbs_by_intervention(user, 'indefinite')
for indefinite in indefinites:
if indefinite not in db.session:
indefinite = db.session.merge(indefinite, load=False)
start = indefinite.calculated_start(trigger_date=trigger_date)
yield start
def calc_and_adjust_start(user, research_study_id, qbd, initial_trigger):
"""Calculate correct start for user on given QBD
A QBD is initially generated with a generic trigger date for
caching and sorting needs. This function translates the
given QBD.relative_start to the users situation.
:param user: subject user
:param research_study_id: research study being processed
:param qbd: QBD with respect to system trigger
:param initial_trigger: datetime value used in initial QBD calculation
:returns adjusted `relative_start` for user
"""
users_trigger = trigger_date(
user, research_study_id=research_study_id, qb=qbd.questionnaire_bank)
if not users_trigger:
trace(
"no valid trigger, default to initial value: {}".format(
initial_trigger))
users_trigger = initial_trigger
if initial_trigger > users_trigger:
trace(
"user {} has unexpected trigger date before consent date".format(
user.id))
if not qbd.relative_start:
raise RuntimeError("can't adjust without relative_start")
if users_trigger == initial_trigger:
return qbd.relative_start
delta = users_trigger - initial_trigger
# this case should no longer be possible; raise the alarm
raise RuntimeError("found initial trigger to differ by: %s", str(delta))
current_app.logger.debug("calc_and_adjust_start delta: %s", str(delta))
return qbd.relative_start + delta
def calc_and_adjust_expired(user, research_study_id, qbd, initial_trigger):
"""Calculate correct expired for user on given QBD
A QBD is initially generated with a generic trigger date for
caching and sorting needs. This function translates the
given QBD.relative_start to the users situation.
:param user: subject user
:param research_study_id: research study being processed
:param qbd: QBD with respect to system trigger
:param initial_trigger: datetime value used in initial QBD calculation
:returns adjusted `relative_start` for user
"""
users_trigger = trigger_date(
user, research_study_id=research_study_id, qb=qbd.questionnaire_bank)
if not users_trigger:
trace(
"no valid trigger, default to initial value: {}".format(
initial_trigger))
users_trigger = initial_trigger
if initial_trigger > users_trigger:
trace(
"user {} has unexpected trigger date before consent date".format(
user.id))
expired = qbd.questionnaire_bank.expired
if not qbd.relative_start:
raise RuntimeError("can't adjust without relative_start")
if users_trigger != initial_trigger:
delta = users_trigger - initial_trigger + RelativeDelta(expired)
current_app.logger.debug(
"calc_and_adjust_expired delta: %s", str(delta))
else:
delta = RelativeDelta(expired)
return qbd.relative_start + delta
max_sort_time = datetime(year=MAXYEAR, month=12, day=31)
def second_null_safe_datetime(x):
"""datetime sort accessor treats None as far off in the future"""
if not x[1]:
return max_sort_time
return x[1]
RPD = namedtuple("RPD", ['rp', 'retired', 'qbds'])
def cur_next_rp_gen(user, research_study_id, classification, trigger_date):
"""Generator to manage transitions through research protocols
Returns a *pair* of research protocol data (RPD) namedtuples,
one for current (active) RP data, one for the "next".
:param user: applicable patient
:param research_study_id: study being processed
:param classification: None or 'indefinite' for special handling
:param trigger_date: patient's initial trigger date
:yields: cur_RPD, next_RPD
"""
rps = ResearchProtocol.assigned_to(user, research_study_id)
sorted_rps = sorted(
list(rps), key=second_null_safe_datetime, reverse=True)
def qbds_for_rp(rp, classification, trigger_date):
if rp is None:
return None
if classification == 'indefinite':
return indef_qbs_by_rp(rp.id, trigger_date=trigger_date)
return ordered_rp_qbs(rp.id, trigger_date=trigger_date)
while sorted_rps:
# Start with oldest RP (current) till it's time to progress (next)
current_rp, current_retired = sorted_rps.pop()
if sorted_rps:
next_rp, next_retired = sorted_rps[-1]
else:
next_rp = None
trace("current RP '{}'({}), next RP '{}'({})".format(
current_rp.name, current_rp.id, next_rp.name
if next_rp else 'None', next_rp.id if next_rp else 'None'))
curRPD = RPD(
rp=current_rp,
retired=current_retired,
qbds=qbds_for_rp(current_rp, classification, trigger_date))
if next_rp:
nextRPD = RPD(
rp=next_rp,
retired=next_retired,
qbds=qbds_for_rp(next_rp, classification, trigger_date)
)
if curRPD.retired == nextRPD.retired:
raise ValueError(
"Invalid state: multiple RPs w/ same retire date")
else:
nextRPD = None
yield curRPD, nextRPD
class RP_flyweight(object):
"""maintains state for RPs as it transitions
Any number of Research Protocols may apply to a user. This
class manages transitioning through the applicable as time
passes, maintaining a "current" and "next" as well as the ability
to continue marching forward.
"""
def __init__(self, user, trigger_date, research_study_id, classification):
"""Initialize flyweight state
:param user: the patient
:param trigger_date: the patient's initial trigger date
:param research_study_id: the study being processed
:param classification: `indefinite` or None
"""
self.user = user
self.td = trigger_date
self.research_study_id = research_study_id
self.classification = classification
self.rp_walker = cur_next_rp_gen(
user=self.user,
research_study_id=self.research_study_id,
trigger_date=self.td,
classification=self.classification)
self.cur_rpd, self.nxt_rpd = next(self.rp_walker, (None, None))
self.skipped_nxt_start = None
def __repr__(self):
"""strictly for enhanced debugging"""
r = []
r.append(
f"current: {self.cur_rpd.rp.name}"
f"(till: {self.cur_rpd.retired}) "
f"cur_qb: [{self.cur_start}<->{self.cur_exp})")
if self.nxt_qbd:
r.append(
f"next: {self.nxt_rpd.rp.name} "
f"next_qb: [{self.nxt_start}<->{self.nxt_exp})")
return '\n'.join(r)
def adjust_start(self):
"""The QB start may need a minor adjustment, done once when ready"""
self.cur_qbd.relative_start = self.cur_start
# sanity check - make sure we don't adjust twice
if hasattr(self.cur_qbd, 'already_adjusted'):
raise RuntimeError(
'already adjusted the qbd relative start')
self.cur_qbd.already_adjusted = True
def consider_transition(self):
"""Returns true only if state suggests it *may* be transtion time"""
return self.nxt_rpd and self.cur_rpd.retired < self.cur_exp
def next_qbd(self):
"""Advance to next qbd on applicable RPs"""
self.cur_qbd, self.cur_start, self.cur_exp = None, None, None
if self.cur_rpd:
self.cur_qbd = next(self.cur_rpd.qbds, None)
if self.cur_qbd:
self.cur_start = calc_and_adjust_start(
user=self.user,
research_study_id=self.research_study_id,
qbd=self.cur_qbd,
initial_trigger=self.td)
self.cur_exp = calc_and_adjust_expired(
user=self.user,
research_study_id=self.research_study_id,
qbd=self.cur_qbd,
initial_trigger=self.td)
self.nxt_qbd, self.nxt_start = None, None
if self.nxt_rpd:
self.nxt_qbd = next(self.nxt_rpd.qbds, None)
if self.nxt_qbd:
self.nxt_start = calc_and_adjust_start(
user=self.user,
research_study_id=self.research_study_id,
qbd=self.nxt_qbd,
initial_trigger=self.td)
self.nxt_exp = calc_and_adjust_expired(
user=self.user,
research_study_id=self.research_study_id,
qbd=self.nxt_qbd,
initial_trigger=self.td)
if self.cur_qbd is None:
trace("Finished cur RP with remaining QBs in next")
self.cur_start = self.nxt_start
self.transition()
elif self.cur_start > self.nxt_start + relativedelta(months=1):
# The plus one month covers RP v5 date adjustments.
# Valid only when the RP being replaced doesn't have all the
# visits defined in the next one (i.e. v3 doesn't have months
# 27 or 33 and v5 does). Look ahead for a match
self.skipped_nxt_start = self.nxt_start
self.nxt_start = None
self.nxt_qbd = next(self.nxt_rpd.qbds, None)
if self.nxt_qbd:
self.nxt_start = calc_and_adjust_start(
user=self.user,
research_study_id=self.research_study_id,
qbd=self.nxt_qbd,
initial_trigger=self.td)
self.nxt_exp = calc_and_adjust_expired(
user=self.user, qbd=self.nxt_qbd,
research_study_id=self.research_study_id,
initial_trigger=self.td)
if self.cur_start > self.nxt_start + relativedelta(months=1):
# Still no match means poorly defined RP QBs
raise ValueError(
"Invalid state {}:{} not in lock-step even on "
"look ahead; RPs need to maintain same "
"schedule {}, {}, {}".format(
self.cur_rpd.rp.name, self.nxt_rpd.rp.name,
self.cur_start, self.nxt_start,
self.skipped_nxt_start))
if self.cur_qbd:
trace("advanced to next QB: {}({}) [{} - {})".format(
self.cur_qbd.questionnaire_bank.name,
self.cur_qbd.iteration,
self.cur_start,
self.cur_exp))
else:
trace("out of QBs!")
def pre_loop_transition(self):
"""Check start state before looping through timeline
If the organization has already retired one or more RPs,
step forward to the correct starting RP
"""
# confirm the now current isn't already retired. rare situation that
# happens when an org has retired multiple RPs before a user's trigger
# historically, Research Protocol changes recorded in persistence
# files include retroactive dates, that is retired values far in the
# past. add a safe buffer as a "look ahead", so we don't move too
# far in the RP history - allowing for the checks in `ordered_qbs()`
# to tie a user to the older, well retired RP if they have submitted
# QuestionnaireResponses defining the older RP.
retro_buffer = relativedelta(months=9)
while True:
# indefinite plays by a different set of rules
if self.classification == 'indefinite':
if (
self.cur_rpd.retired and
self.cur_rpd.retired + retro_buffer < self.td and
self.consider_transition()):
trace('pre-loop transition as RP retired before user trigger')
self.transition()
else:
break
else:
if self.consider_transition() and (
self.cur_rpd.retired + retro_buffer) < self.cur_start:
trace('pre-loop transition')
self.transition()
else:
break
def transition(self):
"""Transition internal state to 'next' Research Protocol"""
trace("transitioning to the next RP [{} - {})".format(
self.cur_start, self.cur_exp))
if self.cur_start > self.nxt_start + relativedelta(months=1):
# The plus one month covers RP v5 shift
raise ValueError(
"Invalid state {}:{} not in lock-step; RPs need "
"to maintain same schedule".format(
self.cur_rpd.rp.name, self.nxt_rpd.rp.name))
self.cur_rpd, self.nxt_rpd = next(self.rp_walker)
# Need to "catch-up" the fresh generators to match current
# if we skipped ahead, only catch-up to the skipped_start
start = self.cur_start
if self.skipped_nxt_start:
assert self.skipped_nxt_start < start
start = self.skipped_nxt_start
entropy_check = 99
while True:
entropy_check -= 1
if entropy_check < 0:
raise RuntimeError("entropy wins again; QB configs out of sync")
self.next_qbd()
if start < self.cur_start + relativedelta(months=1):
# due to early start for RP v5, add a month before comparison
break
# reset in case of another advancement
self.skipped_nxt_start = None
def ordered_qbs(user, research_study_id, classification=None):
"""Generator to yield ordered qbs for a user, research_study
This does NOT include the indefinite classification unless requested,
as it plays by a different set of rules.
:param user: the user to look up
:param research_study_id: the research study being processed
:param classification: set to ``indefinite`` for that special handling
:returns: QBD for each (QB, iteration, recur)
"""
if classification == 'indefinite':
trace("begin ordered_qbds() on `indefinite` classification")
elif classification is not None:
raise ValueError(
"only 'indefinite' or default (None) classifications allowed")
# bootstrap problem - don't know initial `as_of_date` w/o a QB
# call `trigger_date` w/o QB for best guess.
td = trigger_date(user=user, research_study_id=research_study_id)
old_td, withdrawal_date = consent_withdrawal_dates(
user, research_study_id=research_study_id)
if not td:
if old_td and withdrawal_date:
trace("withdrawn user, use previous trigger {}".format(old_td))
td = old_td
else:
trace("no trigger date therefore nothing from ordered_qbds()")
return
else:
trace("initial trigger date {}".format(td))
rp_flyweight = RP_flyweight(
user=user,
trigger_date=td,
research_study_id=research_study_id,
classification=classification)
if rp_flyweight.cur_rpd:
user_qnrs = QNR_results(user, research_study_id=research_study_id)
rp_flyweight.next_qbd()
if not rp_flyweight.cur_qbd:
trace("no current found in initial QBD lookup, bail")
return
rp_flyweight.pre_loop_transition()
while True:
if rp_flyweight.consider_transition():
# if there's a nextRP and curRP is retired before the
# user's QB for the curRP expires, we look to transition
# the user to the nextRP.
#
# if however, the user has already posted QNRs for the
# currentRP one of two things needs to happen:
#
# 1. if any of the QNRs are for instruments which
# deterministically* demonstrate work on the current
# RP has begun, we postpone the transition to the next
# RP till the subsequent "visit" (i.e. next QB which
# will come up in the next iteration)
# 2. if all the submissions for the currentRP are
# non-deterministic*, we transition now and update the
# QNRs so they point to the QB of the nextRP
#
# * over RPs {v2,v3}, "epic23" vs "epic26" deterministically
# define the QB whereas "eortc" is non-deterministic, as
# it belongs to both
transition_now = False
cur_only, common, next_only = left_center_right(
rp_flyweight.cur_qbd.questionnaire_instruments,
rp_flyweight.nxt_qbd.questionnaire_instruments)
combined_instruments = cur_only.union(common).union(next_only)
qnrs_for_period = user_qnrs.authored_during_period(
start=rp_flyweight.cur_start, end=rp_flyweight.cur_exp,
restrict_to_instruments=combined_instruments)
# quick check if current is done, as overlapping QBs pull
# in QNRs from upcoming QBs
unfinished = rp_flyweight.cur_qbd.questionnaire_instruments
for qnr in qnrs_for_period:
if (
qnr.status == 'completed' and
qnr.instrument in unfinished):
unfinished.remove(qnr.instrument)
if len(qnrs_for_period) == 0:
transition_now = True
# Indefinite requires special handling
if classification == 'indefinite' and not unfinished:
yield rp_flyweight.cur_qbd
return
period_instruments = set(
[q.instrument for q in qnrs_for_period])
if not transition_now and period_instruments & cur_only:
# Posted results tie user to the old RP; clear skipped
# state as it's unavailable when results from the "next"
# exist, unless it's all done.
if unfinished:
rp_flyweight.skipped_nxt_start = None
# Don't transition yet, as definitive work on the old
# (current) RP has already been posted, UNLESS ...
if period_instruments & next_only and unfinished:
current_app.logger.warning(
"Transition surprise, {} has deterministic QNRs "
"for multiple RPs '{}':'{}' during same visit; "
"User submitted {}; cur_only {}, common {}, "
"next_only {}. Moving to newer RP".format(
user, rp_flyweight.cur_rpd.rp.name,
rp_flyweight.nxt_rpd.rp.name,
str(period_instruments), str(cur_only),
str(common), str(next_only)))
trace("deterministic for both RPs! transition")
transition_now = True
else:
transition_now = True
if transition_now:
rp_flyweight.transition()
rp_flyweight.adjust_start()
yield rp_flyweight.cur_qbd
rp_flyweight.next_qbd()
if not rp_flyweight.cur_qbd:
return
else:
trace("no RPs found")
# No applicable RPs, try intervention associated QBs
if classification == 'indefinite':
iqbds = indef_intervention_qbs(
user, trigger_date=td)
else:
iqbds = ordered_intervention_qbs(
user, trigger_date=td)
while True:
try:
qbd = next(iqbds)
except StopIteration:
return
users_start = calc_and_adjust_start(
user=user,
research_study_id=research_study_id,
qbd=qbd,
initial_trigger=td)
qbd.relative_start = users_start
# sanity check - make sure we don't adjust twice
if hasattr(qbd, 'already_adjusted'):
raise RuntimeError('already adjusted the qbd relative start')
qbd.already_adjusted = True
yield qbd
def invalidate_users_QBT(user_id, research_study_id):
"""Mark the given user's QBT rows and adherence_data invalid (by deletion)
:param user_id: user for whom to purge all QBT rows
:param research_study_id: set to limit invalidation to research study or
use string 'all' to invalidate all QBT rows for a user
"""
if research_study_id == 'all':
QBT.query.filter(QBT.user_id == user_id).delete()
AdherenceData.query.filter(
AdherenceData.patient_id == user_id).delete()
else:
QBT.query.filter(QBT.user_id == user_id).filter(
QBT.research_study_id == research_study_id).delete()
adh_data = AdherenceData.query.filter(
AdherenceData.patient_id == user_id).filter(
AdherenceData.rs_id_visit.like(f"{research_study_id}:%"))
# SQL alchemy can't combine `like` expression with delete op.
for ad in adh_data:
db.session.delete(ad)
if not current_app.config.get("TESTING", False):
# clear the timeout lock as well, since we need a refresh
# after deletion of the adherence data
# otherwise, we experience a deadlock situation where tables can't be dropped
# between test runs, as postgres believes a deadlock condition exists
cache_moderation = CacheModeration(key=ADHERENCE_DATA_KEY.format(
patient_id=user_id,
research_study_id=research_study_id))
cache_moderation.reset()
# args have to match order and values - no wild carding avail
as_of = QB_StatusCacheKey().current()
if research_study_id != 'all':
cache.delete_memoized(
qb_status_visit_name, user_id, research_study_id, as_of)
else:
# quicker to just clear both than look up what user belongs to
cache.delete_memoized(
qb_status_visit_name, user_id, 0, as_of)
cache.delete_memoized(
qb_status_visit_name, user_id, 1, as_of)
db.session.commit()
def check_for_overlaps(qbt_rows, cli_presentation=False):
"""Sanity function to confirm users timeline doesn't contain overlaps"""
# Expect ordered rows with increasing `at` values. Track (QB,iterations)
# seen, notify if overlaps are discovered.
from .questionnaire_bank import QuestionnaireBank
def rp_name_from_qb_id(qb_id):
return ResearchProtocol.query.join(QuestionnaireBank).filter(
QuestionnaireBank.research_protocol_id ==
ResearchProtocol.id).filter(
QuestionnaireBank.id == qb_id).with_entities(
ResearchProtocol.name).first()[0]
def int_or_none(value):
"""None safe int cast from string"""
if value is None or value == 'None':
return None
return int(value)
seen = set()
last_at, previous_key = None, None
reported_on = set()
for row in qbt_rows:
# Confirm expected order
if last_at:
assert row.at >= last_at
key = f"{row.qb_id}:{row.qb_iteration}"
if previous_key and previous_key != key:
# just moved to next visit, confirm it's novel
if key in seen:
overlap = row.at - last_at
if overlap and not (key in reported_on and previous_key in reported_on):
qb_id, iteration = [
int_or_none(x) for x in previous_key.split(':')]
prev_visit = " ".join(
(visit_name(qbd=QBD(
relative_start=None,
iteration=iteration,
qb_id=qb_id,
recur_id=previous_recur_id)),
rp_name_from_qb_id(qb_id)))
visit = " ".join(
(visit_name(qbd=QBD(
relative_start=None,
iteration=row.qb_iteration,
qb_id=row.qb_id,
recur_id=row.qb_recur_id)),
rp_name_from_qb_id(row.qb_id)))
m = (
f"{visit}, {prev_visit} overlap by {overlap} for"
f" {row.user_id}")
if cli_presentation:
print(m)
else:
current_app.logger.error(m)
# Don't report the back and forth, once is adequate.
reported_on.add(key)
reported_on.add(previous_key)
previous_key = key
previous_recur_id = row.qb_recur_id
seen.add(key)
last_at = row.at
if reported_on:
# Returns true if at least one overlap was found
return True
def update_users_QBT(user_id, research_study_id, invalidate_existing=False):
"""Populate the QBT rows for given user, research_study
:param user: the user to add QBT rows for
:param research_study_id: the research study being processed
:param invalidate_existing: set true to wipe any current rows first
A user may be eligible for any number of research studies. QBT treats
each (user, research_study) independently, as should clients.
"""
def attempt_update(user_id, research_study_id, invalidate_existing):
"""Updates user's QBT or raises if lock is unattainable"""
from .qb_status import patient_research_study_status
from ..tasks import LOW_PRIORITY, cache_single_patient_adherence_data
# acquire a multiprocessing lock to prevent multiple requests
# from duplicating rows during this slow process
timeout = int(current_app.config.get("MULTIPROCESS_LOCK_TIMEOUT"))
key = "update_users_QBT user:study {}:{}".format(
user_id, research_study_id)
with TimeoutLock(key=key, timeout=timeout):
if invalidate_existing:
QBT.query.filter(QBT.user_id == user_id).filter(
QBT.research_study_id == research_study_id).delete()
adh_data = AdherenceData.query.filter(
AdherenceData.patient_id == user_id).filter(
AdherenceData.rs_id_visit.like(f"{research_study_id}:%")
)
# SQL alchemy can't combine `like` expression with delete op.
for ad in adh_data:
db.session.delete(ad)
db.session.commit()
# if any rows are found, assume this user/study is current
if QBT.query.filter(QBT.user_id == user_id).filter(
QBT.research_study_id == research_study_id).count():
trace(
"found QBT rows, returning cached for {}:{}".format(
user_id, research_study_id))
return
user = User.query.get(user_id)
if not user.has_role(ROLE.PATIENT.value):
# Make it easier to find bogus use, by reporting user
# and their roles in exception
raise ValueError(
"{} with roles {} doesn't have timeline, only "
"patients".format(
user, str([r.name for r in user.roles])))
# Check eligibility - some studies aren't available till
# business rules have been met
rss = patient_research_study_status(user, ignore_QB_status=True)
study_eligibility = (
research_study_id in rss and rss[research_study_id]['eligible'])
if not study_eligibility:
trace(f"user determined ineligible for {research_study_id}")
return
# Create time-line for user, from initial trigger date
qb_generator = ordered_qbs(user, research_study_id)
user_qnrs = QNR_results(user, research_study_id)
# Force recalculation of QNR->QB association if needed
if user_qnrs.qnrs_missing_qb_association():
user_qnrs.assign_qb_relationships(qb_generator=ordered_qbs)
# As we move forward, capture state at each time point
kwargs = {
"user_id": user.id,
"research_study_id": research_study_id,
}
pending_qbts = AtOrderedList()
for qbd in qb_generator:
qb_recur_id = qbd.recur.id if qbd.recur else None
kwargs = {
"user_id": user.id,
"research_study_id": research_study_id,
"qb_id": qbd.questionnaire_bank.id,
"qb_iteration": qbd.iteration,
"qb_recur_id": qb_recur_id}
start = qbd.relative_start
if (
pending_qbts and pending_qbts[-1].at > start and
pending_qbts[-1].status == 'expired'):
# Found overlapping visits. Move the expired date of
# previous just before start if possible
# (no additional rows with at dates > start)
other_status_after_next_start = False
for i in range(len(pending_qbts)-2, -1, -1):
# as we modify len of pending_qbts in special case below
# make sure next iteration is within new bounds
if i > len(pending_qbts)-1:
continue
unwanted_count = 0
if pending_qbts[i].at > start:
# Yet another special case to look for when the
# transition to new RP included an additional
# time-point (say month 33) that doesn't exist in
# the old RP. This will appear as TWO overlapping
# QBs - one needing to be removed (say the old
# month 36) in favor of the skipped new (say
# month 33), and the last legit old one (say
# month 30) needing its endpoint adjusted
# further below.
remove_qb_id = pending_qbts[i].qb_id
remove_iteration = pending_qbts[i].qb_iteration
for j in range(i-1, -1, -1):
# keep looking back till we find the prev
if (
pending_qbts[j].qb_id != remove_qb_id or
pending_qbts[j].qb_iteration != remove_iteration):
# To qualify for this special case,
# having worked back to previous QB, if
# at > start, take action
if pending_qbts[j].at > start:
unwanted_count = len(pending_qbts)-j-1
break
# keep a lookout for work done in old RP
if pending_qbts[j].status in (
'in_progress',
'partially_completed',
'completed'):
other_status_after_next_start = True
break
if other_status_after_next_start:
break # from outer loop if set
# Remove unwanted from end of pending_qbts
if unwanted_count:
trace(
"removing overlapping QBs: "
f"{pending_qbts[-unwanted_count:]}")