-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutilities.py
2264 lines (2088 loc) · 131 KB
/
utilities.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
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import sys
import pickle
from scipy import optimize
from scipy.optimize import least_squares
import scipy.stats
from copy import deepcopy
import time
import warnings
from multiprocessing import Pool
#from drug_colors import *
#import seaborn as sns
import arviz as az
import pymc as pm
import gc # Garbage collector
def isNaN(string):
return string != string
def Sort(sub_li): # Sorts a list of sublists on the second element in the list
return(sorted(sub_li, key = lambda x: x[1]))
def find_max_time(measurement_times):
# Plot until last measurement time (last in array, or first nan in array)
if np.isnan(measurement_times).any():
last_time_index = np.where(np.isnan(measurement_times))[0][0] -1 # Last non-nan index
else:
last_time_index = -1
return int(measurement_times[last_time_index])
def print_map(result):
return pd.Series({k: v for k, v in result.items()})
s = 25 # scatter plot object size
GROWTH_LB = 0.001
PI_LB = 0.001
# Bounds for model 1: 1 population, only resistant cells
# Y_0, g_r sigma
lb_1 = np.array([ 0, GROWTH_LB, 10e-6])
ub_1 = np.array([100, 0.20, 10e4])
# Bounds for model 2: 1 population, only sensitive cells
# Y_0, g_s, k_1, sigma
lb_2 = np.array([ 0, GROWTH_LB, 0.20, 10e-6])
ub_2 = np.array([100, lb_2[2], 1.00, 10e4])
# Bounds for model 3: sensitive and resistant population
# Y_0, pi_r, g_r, g_s, k_1, sigma
lb_3 = np.array([ 0, PI_LB, GROWTH_LB, GROWTH_LB, 0.20, 10e-6])
ub_3 = np.array([100, 1-PI_LB, 0.20, lb_3[4], 1.00, 10e4])
# Suggested from the server, as more informative:
#lb_3 = np.array([ 0, PI_LB, GROWTH_LB, GROWTH_LB, 0.002, 10e-6])
#ub_3 = np.array([100, 1-PI_LB, 0.20, lb_3[4], 0.2, 10e4])
np.random.seed(42)
from numpy.random import MT19937
from numpy.random import RandomState, SeedSequence
rs = RandomState(MT19937(SeedSequence(123456789)))
## Later, you want to restart the stream
#rs = RandomState(MT19937(SeedSequence(987654321)))
# Assumptions and definitions:
# The atomic unit of time is 1 day
# Treatment lines must be back to back: Start of a treatment must equal end of previous treatment
# Growth rates are in unit 1/days
# 22.03.22 treatment in terms of different drugs
# In drug dictionary, key is drug name and value is drug id
treatment_id_to_drugs_dictionary = {}
drug_dictionary_OSLO = {}
drug_dictionary = {}
#drug_dictionary_OSLO = np.load("./binaries_and_pickles/drug_dictionary_OSLO.npy", allow_pickle=True).item()
#drug_dictionary_COMMPASS = np.load("./binaries_and_pickles/drug_dictionary_COMMPASS.npy", allow_pickle=True).item()
#for key, value in drug_dictionary_COMMPASS.items():
# if key not in drug_dictionary_OSLO.keys():
# drug_dictionary_OSLO[key] = (max(drug_dictionary_OSLO.values())+1)
# Join the two drug dictionaries to get a complete drug dictionary
#drug_dictionary = drug_dictionary_OSLO
#np.save("./binaries_and_pickles/drug_dictionary.npy", drug_dictionary)
#drug_id_to_name_dictionary = {v: k for k, v in drug_dictionary.items()}
#treatment_to_id_dictionary = np.load("./binaries_and_pickles/treatment_to_id_dictionary_OSLO.npy", allow_pickle=True).item()
##treatment_to_id_dictionary = np.load("./binaries_and_pickles/treatment_to_id_dictionary_COMMPASS.npy", allow_pickle=True).item()
#treatment_id_to_drugs_dictionary = {v: k for k, v in treatment_to_id_dictionary.items()}
#def get_drug_names_from_treatment_id_COMMPASS(treatment_id, treatment_id_to_drugs_dictionary_COMMPASS):
# drug_set = treatment_id_to_drugs_dictionary_COMMPASS[treatment_id]
# drug_names = [drug_id_to_name_dictionary[elem] for elem in drug_set]
# return drug_names
#unique_drugs = ['Revlimid (lenalidomide)', 'Cyclophosphamide', 'Pomalidomide',
# 'Thalidomide', 'Velcade (bortezomib) - subcut twice weekly',
# 'Dexamethasone', 'Velcade (bortezomib) - subcut once weekly', 'Carfilzomib',
# 'Melphalan', 'Panobinostat', 'Daratumumab', 'Velcade i.v. twice weekly',
# 'Bendamustin', 'Methotrexate i.t.', 'Prednisolon', 'pembrolizumab',
# 'Pembrolizumab', 'Doxorubicin', 'Velcade i.v. once weekly', 'Vincristine',
# 'Ibrutinib', 'lxazomib', 'Cytarabin i.t.', 'Solu-Medrol',
# 'Velcade s.c. every 2nd week', 'Clarithromycin', 'hydroxychloroquine',
# 'Metformin', 'Rituximab']
#drug_ids = range(len(unique_drugs))
#drug_dictionary_OSLO = dict(zip(unique_drugs, drug_ids))
#unique_treatment_lines = []
#drug_ids = range(len(unique_treatment_lines))
#treatment_to_id_dictionary = dict(zip(unique_treatment_lines, treatment_line_ids))
#####################################
# Classes, functions
#####################################
class Cell_population:
# alpha is the growth rate with no drug
# k_d is the additive effect of drug d on the growth rate
def __init__(self, alpha, k_1, k_2, k_3, k_4, k_5, k_6, k_7, k_8, k_9):
self.alpha = alpha
self.k_1 = k_1
self.k_2 = k_2
self.k_3 = k_3
self.k_4 = k_4
self.k_5 = k_5
self.k_6 = k_6
self.k_7 = k_7
self.k_8 = k_8
self.k_9 = k_9
self.drug_effects = [k_1, k_2, k_3, k_4, k_5, k_6, k_7, k_8, k_9]
def get_growth_rate(self, treatment):
this_drug_array = treatment.get_drug_ids()
drug_effect_filter = [drug_id in this_drug_array for drug_id in range(len(self.drug_effects))]
print(drug_effect_filter)
return self.alpha - sum(self.drug_effects[drug_effect_filter])
class Parameters:
def __init__(self, Y_0, pi_r, g_r, g_s, k_1, sigma):
self.Y_0 = Y_0 # M protein value at start of treatment
self.pi_r = pi_r # Fraction of resistant cells at start of treatment
self.g_r = g_r # Growth rate of resistant cells
self.g_s = g_s # Growth rate of sensitive cells in absence of treatment
self.k_1 = k_1 # Additive effect of treatment on growth rate of sensitive cells
self.sigma = sigma # Standard deviation of measurement noise
def to_array_without_sigma(self):
return np.array([self.Y_0, self.pi_r, self.g_r, self.g_s, self.k_1])
def to_array_with_sigma(self):
return np.array([self.Y_0, self.pi_r, self.g_r, self.g_s, self.k_1, self.sigma])
def to_array_for_prediction(self):
return np.array([self.pi_r, self.g_r, (self.g_s - self.k_1)])
def to_prediction_array_composite_g_s_and_K_1(self):
return [self.pi_r, self.g_r, (self.g_s - self.k_1)]
class Treatment:
def __init__(self, start, end, id):
self.start = start
self.end = end
self.id = id
def get_drug_ids(self):
return [drug_dictionary_OSLO[drug_name] for drug_name in treatment_id_to_drugs_dictionary[self.id]]
class Drug_period:
def __init__(self, start, end, id):
self.start = start
self.end = end
self.id = id
class Patient:
def __init__(self, parameters, measurement_times, treatment_history, covariates = [], name = "nn"):
self.measurement_times = measurement_times
self.treatment_history = treatment_history
self.Mprotein_values = measure_Mprotein_with_noise(parameters, self.measurement_times, self.treatment_history)
self.covariates = covariates
self.name = name
self.longitudinal_data = {} # dictionary where the keys are covariate_names, the entries numpy arrays!
self.longitudinal_times = {} # matching time arrays for each covariate
self.pfs = []
self.mrd_results = []
self.mrd_times = []
def get_measurement_times(self):
return self.measurement_times
def get_treatment_history(self):
return self.treatment_history
def get_Mprotein_values(self):
return self.Mprotein_values
def get_covariates(self):
return self.covariates
class Real_Patient:
def __init__(self, measurement_times, Mprotein_values, covariates=[], name="no_id", pfs=np.nan):
self.measurement_times = measurement_times # numpy array
self.treatment_history = np.array([Treatment(start=1, end=measurement_times[-1], id=1)])
self.Mprotein_values = Mprotein_values # numpy array
self.covariates = covariates # Optional
self.name = name # id
self.longitudinal_data = {} # dictionary where the keys are covariate_names, the entries numpy arrays!
self.longitudinal_times = {} # matching time arrays for each covariate
self.pfs = pfs
#self.KappaLambdaRatio = [np.nan for elem in measurement_times] # This is part of longitudinals
self.mrd_results = []
self.mrd_times = []
def get_treatment_history(self):
return self.treatment_history
def get_Mprotein_values(self):
return self.Mprotein_values
def get_measurement_times(self):
return self.measurement_times
def get_covariates(self):
return self.covariates
def add_Mprotein_line_to_patient(self, time, Mprotein):
self.measurement_times = np.append(self.measurement_times,[time])
self.treatment_history = np.array([Treatment(start=1, end=time, id=1)])
self.Mprotein_values = np.append(self.Mprotein_values,[Mprotein])
return 0
class COMMPASS_Patient:
def __init__(self, measurement_times, drug_dates, drug_history, treatment_history, Mprotein_values, Kappa_values, Lambda_values, covariates, name):
self.name = name # string: patient id
self.measurement_times = measurement_times # numpy array: dates for M protein measurements in Mprotein_values
self.Mprotein_values = Mprotein_values # numpy array: M protein measurements
self.drug_history = drug_history # numpy array of possibly overlapping single Drug_period instances, a pre-step to make treatment_history
self.drug_dates = drug_dates # set: set of drug dates that marks the intervals
self.treatment_history = treatment_history # numpy array of non-overlapping Treatment instances (drug combinations) sorted by occurrence
self.covariates = covariates # ?? : other covariates
self.parameter_estimates = np.array([])
self.parameter_periods = np.array([])
self.dummmy_patients = np.array([])
self.Kappa_values = Kappa_values
self.Lambda_values = Lambda_values
def get_measurement_times(self):
return self.measurement_times
def get_treatment_history(self):
return self.treatment_history
def get_drug_history(self):
return self.drug_history
def get_Mprotein_values(self):
return self.Mprotein_values
def print(self):
print("\nPrinting patient "+self.name)
print("M protein values:")
print(self.Mprotein_values)
print("Measurement times:")
print(self.measurement_times)
print("Drug history:")
for number, drug_period in enumerate(self.drug_history):
print(str(number) + ": [",drug_period.start, "-", drug_period.end, "]: drug id", drug_period.id)
print("Treatment history:")
for number, treatment in enumerate(self.treatment_history):
print(str(number) + ": [",treatment.start, "-", treatment.end, "]: treatment id", treatment.id)
if len(self.parameter_estimates) > 0:
print("Estimated parameters by period:")
for number, parameters in enumerate(self.parameter_estimates):
print(parameters.to_array_without_sigma(), "in", self.parameter_periods[number])
def add_Mprotein_line_to_patient(self, time, Mprotein, Kappa, Lambda):
self.measurement_times = np.append(self.measurement_times,[time])
self.Mprotein_values = np.append(self.Mprotein_values,[Mprotein])
self.Kappa_values = np.append(self.Kappa_values,[Kappa])
self.Lambda_values = np.append(self.Lambda_values,[Lambda])
return 0
def add_drug_period_to_patient(self, drug_period_object):
self.drug_history = np.append(self.drug_history,[drug_period_object])
self.drug_dates.add(drug_period_object.start)
self.drug_dates.add(drug_period_object.end)
return 0
def add_treatment_to_treatment_history(self, treatment_object):
self.treatment_history = np.append(self.treatment_history,[treatment_object])
return 0
def add_parameter_estimate(self, estimates, period, dummmy_patient):
#if len(self.parameter_estimates) == 0:
# self.parameter_estimates = np.zeros(len(self.treatment_history))
self.parameter_estimates = np.append(self.parameter_estimates,[estimates])
if len(self.parameter_periods) == 0:
self.parameter_periods = np.array([period])
self.dummmy_patients = np.array([dummmy_patient])
else:
self.parameter_periods = np.append(self.parameter_periods, np.array([period]), axis=0)
self.dummmy_patients = np.append(self.dummmy_patients, np.array([dummmy_patient]), axis=0)
class Filter:
def __init__(self, filter_type, bandwidth, lag):
self.filter_type = filter_type # flat or gauss
self.bandwidth = bandwidth # days
self.lag = lag # days
def compute_drug_filter_values(this_filter, patient, end_of_history): # end_of_history: The time at which history ends and the treatment of interest begins
# Returns a dictionary with key: drug_id (string) and value: filter feature value (float) for all drugs
filter_end = max(0, end_of_history - this_filter.lag)
filter_start = max(0, end_of_history - this_filter.lag - this_filter.bandwidth)
# Loop through drug periods in patient history and update the filter values by computing overlap with filter interval
#filter_value_dictionary = {k: 0 for k, v in drug_dictionary.items()}
filter_values = [0 for ii in range(len(drug_dictionary))]
for drug_period in patient.drug_history:
# Overlap = min(ends) - max(starts)
overlap = min(drug_period.end, filter_end) - max(drug_period.start, filter_start)
# Set 0 if negative
filter_addition = max(0, overlap)
#filter_value_dictionary[drug_period.id] = filter_value_dictionary[drug_period.id] + filter_addition
filter_values[drug_period.id] = filter_values[drug_period.id] + filter_addition
return filter_values
# This function is vectorized w.r.t different filters only, not drug ids or drug periods because two drug periods can have the same drug id
def compute_filter_values(this_filter, patient, end_of_history, value_type="Mprotein"): # end_of_history: The time at which history ends and the treatment of interest begins
# Returns a dictionary with key: drug_id (string) and value: filter feature value (float) for all drugs
filter_end = max(0, end_of_history - this_filter.lag)
filter_start = max(0, end_of_history - this_filter.lag - this_filter.bandwidth)
correct_times = (patient.measurement_times >= filter_start) & (patient.measurement_times <= filter_end)
if value_type == "Mprotein":
type_values = patient.Mprotein_values[correct_times]
elif value_type == "Kappa":
type_values = patient.Kappa_values[correct_times]
elif value_type == "Lambda":
type_values = patient.Lambda_values[correct_times]
# Automatically handling empty lists since sum([]) = 0.
if this_filter.filter_type == "flat":
filter_values = [sum(type_values)]
elif this_filter.filter_type == "gauss":
# For Gaussian filters, lag = offset and bandwidth = variance
values = type_values
time_deltas = patient.measurement_times[correct_times] - filter_end
gauss_weighting = scipy.stats.norm(filter_end, this_filter.bandwidth).pdf(time_deltas)
filter_values = [sum(gauss_weighting * values)]
return filter_values
#####################################
# Generative models, simulated data
#####################################
# Efficient implementation
# Simulates M protein value at times [t + delta_T]_i
# Y_t is the M protein level at start of time interval
def generative_model(Y_t, params, delta_T_values, drug_effect):
return Y_t * params.pi_r * np.exp(params.g_r * delta_T_values) + Y_t * (1-params.pi_r) * np.exp((params.g_s - drug_effect) * delta_T_values)
def generate_resistant_Mprotein(Y_t, params, delta_T_values, drug_effect):
return Y_t * params.pi_r * np.exp(params.g_r * delta_T_values)
def generate_sensitive_Mprotein(Y_t, params, delta_T_values, drug_effect):
return Y_t * (1-params.pi_r) * np.exp((params.g_s - drug_effect) * delta_T_values)
def get_pi_r_after_time_has_passed(params, measurement_times, treatment_history):
Mprotein_values = np.zeros_like(measurement_times, dtype=float) #without dtype you get ints
# Adding a small epsilon to Y and pi_r to improve numerical stability
epsilon_value = 1e-15
Y_t = params.Y_0# + epsilon_value
pi_r_t = params.pi_r# + epsilon_value
t_params = Parameters(Y_t, pi_r_t, params.g_r, params.g_s, params.k_1, params.sigma)
for treat_index in range(len(treatment_history)):
# Find the correct drug effect k_1
this_treatment = treatment_history[treat_index]
if this_treatment.id == 0:
drug_effect = 0
#elif this_treatment.id == 1:
# With inference only for individual combinations at a time, it is either 0 or "treatment on", which is k1
else:
drug_effect = t_params.k_1
#else:
# sys.exit("Encountered treatment id with unspecified drug effect in function: measure_Mprotein")
# Filter that selects measurement times occuring while on this treatment line
correct_times = (measurement_times >= this_treatment.start) & (measurement_times <= this_treatment.end)
delta_T_values = measurement_times[correct_times] - this_treatment.start
# Add delta T for (end - start) to keep track of Mprotein at end of treatment
delta_T_values = np.concatenate((delta_T_values, np.array([this_treatment.end - this_treatment.start])))
# Calculate Mprotein values
# resistant
resistant_mprotein = generate_resistant_Mprotein(Y_t, t_params, delta_T_values, drug_effect)
# sensitive
sensitive_mprotein = generate_sensitive_Mprotein(Y_t, t_params, delta_T_values, drug_effect)
# summed
recorded_and_endtime_mprotein_values = resistant_mprotein + sensitive_mprotein
# Assign M protein values for measurement times that are in this treatment period
Mprotein_values[correct_times] = recorded_and_endtime_mprotein_values[0:-1]
# Store Mprotein value at the end of this treatment:
Y_t = recorded_and_endtime_mprotein_values[-1]# + epsilon_value
pi_r_t = resistant_mprotein[-1] / (resistant_mprotein[-1] + sensitive_mprotein[-1] + epsilon_value) # Add a small number to keep numerics ok
t_params = Parameters(Y_t, pi_r_t, t_params.g_r, t_params.g_s, t_params.k_1, t_params.sigma)
return Mprotein_values, pi_r_t
# Input: a Parameter object, a numpy array of time points in days, a list of back-to-back Treatment objects
def measure_Mprotein_noiseless(params, measurement_times, treatment_history):
Mprotein_values, pi_r_after_time_has_passed = get_pi_r_after_time_has_passed(params, measurement_times, treatment_history)
return Mprotein_values
# Input: a Parameter object, a numpy array of time points in days, a list of back-to-back Treatment objects
def measure_Mprotein_with_noise(params, measurement_times, treatment_history):
# Return true M protein value + Noise
noise_array = np.random.normal(0, params.sigma, len(measurement_times))
noisy_observations = measure_Mprotein_noiseless(params, measurement_times, treatment_history) + noise_array
# thresholded at 0
return np.array([max(0, value) for value in noisy_observations])
# Pass a Parameter object to this function along with an numpy array of time points in days
def measure_Mprotein_naive(params, measurement_times, treatment_history):
Mprotein_values = np.zeros_like(measurement_times)
Y_t = params.Y_0
for treat_index in range(len(treatment_history)):
# Find the correct drug effect k_1
if treatment_history[treat_index].id == 0:
drug_effect = 0
elif treatment_history[treat_index].id == 1:
drug_effect = params.k_1
else:
print("Encountered treatment id with unspecified drug effect in function: measure_Mprotein")
sys.exit("Encountered treatment id with unspecified drug effect in function: measure_Mprotein")
# Calculate the M protein value at the end of this treatment line
Mprotein_values = params.Y_0 * params.pi_r * np.exp(params.g_r * measurement_times) + params.Y_0 * (1-params.pi_r) * np.exp((params.g_s - drug_effect) * measurement_times)
return Mprotein_values
#return params.Y_0 * params.pi_r * np.exp(params.g_r * measurement_times) + params.Y_0 * (1-params.pi_r) * np.exp((params.g_s - params.k_1) * measurement_times)
def generate_simulated_patients(measurement_times, treatment_history, true_sigma_obs, N_patients_local, P, get_expected_theta_from_X, true_omega, true_omega_for_psi, seed, RANDOM_EFFECTS, DIFFERENT_LENGTHS=True, USUBJID=False, simulate_rho_r_dependancy_on_rho_s=False, coef_rho_s_rho_r=0, psi_population=50, crop_after_pfs=False):
np.random.seed(seed)
#X_mean = np.repeat(0,P)
#X_std = np.repeat(0.5,P)
#X = np.random.normal(X_mean, X_std, size=(N_patients_local,P))
X = np.random.uniform(-1, 1, size=(N_patients_local,P))
X = pd.DataFrame(X, columns = ["Covariate "+str(ii+1) for ii in range(P)])
expected_theta_1, expected_theta_2, expected_theta_3 = get_expected_theta_from_X(X, simulate_rho_r_dependancy_on_rho_s, coef_rho_s_rho_r)
if USUBJID:
X["USUBJID"] = ["Patient " + x for x in X.index.map(str)]
# Set the seed again to make the random effects not change with P
np.random.seed(seed+1)
if RANDOM_EFFECTS:
true_theta_rho_s = np.random.normal(expected_theta_1, true_omega[0])
true_theta_rho_r = np.random.normal(expected_theta_2, true_omega[1])
true_theta_pi_r = np.random.normal(expected_theta_3, true_omega[2])
else:
true_theta_rho_s = expected_theta_1
true_theta_rho_r = expected_theta_2
true_theta_pi_r = expected_theta_3
# Set the seed again to get identical observation noise irrespective of random effects or not
np.random.seed(seed+2)
true_theta_psi = np.random.normal(np.log(psi_population), true_omega_for_psi, size=N_patients_local)
true_rho_s = - np.exp(true_theta_rho_s)
true_rho_r = np.exp(true_theta_rho_r)
true_pi_r = 1/(1+np.exp(-true_theta_pi_r))
true_psi = np.exp(true_theta_psi)
# Set seed again to give patient random Numbers of M protein
np.random.seed(seed+3)
parameter_dictionary = {}
patient_dictionary = {}
for training_instance_id in range(N_patients_local):
psi_patient_i = true_psi[training_instance_id]
pi_r_patient_i = true_pi_r[training_instance_id]
rho_r_patient_i = true_rho_r[training_instance_id]
rho_s_patient_i = true_rho_s[training_instance_id]
these_parameters = Parameters(Y_0=psi_patient_i, pi_r=pi_r_patient_i, g_r=rho_r_patient_i, g_s=rho_s_patient_i, k_1=0, sigma=true_sigma_obs)
# Remove some measurement times from the end:
if DIFFERENT_LENGTHS:
M_ii = np.random.randint(min(3,len(measurement_times)), len(measurement_times)+1)
else:
M_ii = len(measurement_times)
measurement_times_ii = measurement_times[:M_ii]
this_patient = Patient(these_parameters, measurement_times_ii, treatment_history, name=str(training_instance_id))
patient_dictionary["Patient " + str(training_instance_id)] = this_patient
# From server:
#patient_dictionary[training_instance_id] = this_patient
parameter_dictionary[training_instance_id] = these_parameters
#plot_true_mprotein_with_observations_and_treatments_and_estimate(these_parameters, this_patient, estimated_parameters=[], PLOT_ESTIMATES=False, plot_title=str(training_instance_id), savename="./plots/Bayes_simulated_data/"+str(training_instance_id)
if crop_after_pfs:
true_pfs_complete_patient_dictionary = get_true_pfs_new(patient_dictionary, time_scale=1, M_scale=1)
# Crop measurements afer progression:
for ii, patient in enumerate(patient_dictionary.values()):
if true_pfs_complete_patient_dictionary[ii] > 0:
patient.Mprotein_values = patient.Mprotein_values[patient.measurement_times <= true_pfs_complete_patient_dictionary[ii]] # + 2*28]
patient.measurement_times = patient.measurement_times[patient.measurement_times <= true_pfs_complete_patient_dictionary[ii]] # + 2*28]
return X, patient_dictionary, parameter_dictionary, expected_theta_1, true_theta_rho_s, true_rho_s
#return X, patient_dictionary, parameter_dictionary, expected_theta_1, true_theta_rho_s, true_rho_s, expected_theta_2, true_theta_rho_r, true_rho_r, expected_theta_3, true_theta_pi_r, true_pi_r
#####################################
# Plotting
#####################################
#treat_colordict = dict(zip(treatment_line_ids, treat_line_colors))
def plot_mprotein(patient, title, savename, PLOT_PARAMETERS=False, parameters = [], PLOT_lightchains=False, plot_pfs=False, plot_KapLam=False):
measurement_times = patient.measurement_times
Mprotein_values = patient.Mprotein_values
fig, ax1 = plt.subplots()
ax1.plot(measurement_times, Mprotein_values, linestyle='', marker='x', zorder=3, color='k', label="Observed M protein")
if PLOT_lightchains:
ax1.plot(measurement_times, Mprotein_values, linestyle='', marker='x', zorder=3, color='b', label="Observed M protein")
if plot_pfs:
ax1.axvline(patient.pfs, color="r", linewidth=1, linestyle="--", label="PFS")
if plot_KapLam:
#ax1.plot(measurement_times, patient.KappaLambdaRatio, linestyle='-', marker='x', zorder=2, color='g', label="Kappa/Lambda ratio")
ax1.plot(patient.longitudinal_times["Kappa Lt Chain,Free/Lambda Lt Chain,Free (RATIO)"], patient.longitudinal_data["Kappa Lt Chain,Free/Lambda Lt Chain,Free (RATIO)"], linestyle='-', marker='x', zorder=2, color='g', label="Kappa/Lambda ratio")
if PLOT_PARAMETERS:
plotting_times = np.linspace(measurement_times[0], measurement_times[-1], 80)
treatment_history = np.array([Treatment(start=measurement_times[0], end=measurement_times[-1], id=1)])
# Plot true M protein curves according to parameters
plotting_mprotein_values = measure_Mprotein_noiseless(parameters, plotting_times, treatment_history)
# Count resistant part
resistant_parameters = Parameters((parameters.Y_0*parameters.pi_r), 1, parameters.g_r, parameters.g_s, parameters.k_1, parameters.sigma)
plotting_resistant_mprotein_values = measure_Mprotein_noiseless(resistant_parameters, plotting_times, treatment_history)
# sens
ax1.plot(plotting_times, plotting_mprotein_values-plotting_resistant_mprotein_values, linestyle='--', marker='', zorder=3, color='b') #, label="True M protein (total)")
# Plot resistant M protein
ax1.plot(plotting_times, plotting_resistant_mprotein_values, linestyle='--', marker='', zorder=2.9, color="r") #, label="True M protein (resistant)")
# Plot total M protein
ax1.plot(plotting_times, plotting_mprotein_values, linestyle='-', marker='', zorder=3, color='k') #, label="True M protein (total)")
ax1.set_title(title)
ax1.set_xlabel("Days")
ax1.set_ylabel("Serum M protein (g/L)")
ax1.set_ylim(bottom=0, top=85) # Not on server
ax1.set_zorder(ax1.get_zorder()+3)
ax1.legend()
fig.tight_layout()
plt.savefig(savename,dpi=300)
plt.close()
def plot_true_mprotein_with_observations_and_treatments_and_estimate(true_parameters, patient, estimated_parameters=[], PLOT_ESTIMATES=False, plot_title="Patient 1", savename=0):
measurement_times = patient.get_measurement_times()
treatment_history = patient.get_treatment_history()
Mprotein_values = patient.get_Mprotein_values()
first_time = min(measurement_times[0], treatment_history[0].start)
max_time = find_max_time(measurement_times)
plotting_times = np.linspace(first_time, max_time, int((measurement_times[-1]+1)*10))
# Plot true M protein values according to true parameters
plotting_mprotein_values = measure_Mprotein_noiseless(true_parameters, plotting_times, treatment_history)
# Count resistant part
resistant_parameters = Parameters((true_parameters.Y_0*true_parameters.pi_r), 1, true_parameters.g_r, true_parameters.g_s, true_parameters.k_1, true_parameters.sigma)
plotting_resistant_mprotein_values = measure_Mprotein_noiseless(resistant_parameters, plotting_times, treatment_history)
# Plot M protein values
plotheight = 1
maxdrugkey = 2
fig, ax1 = plt.subplots()
ax1.patch.set_facecolor('none')
# Plot sensitive and resistant
ax1.plot(plotting_times, plotting_resistant_mprotein_values, linestyle='-', marker='', zorder=3, color='r', label="True M protein (resistant)")
# Plot total M protein
ax1.plot(plotting_times, plotting_mprotein_values, linestyle='-', marker='', zorder=3, color='k', label="True M protein (total)")
if PLOT_ESTIMATES:
# Plot estimtated Mprotein line
estimated_mprotein_values = measure_Mprotein_noiseless(estimated_parameters, plotting_times, treatment_history)
ax1.plot(plotting_times, estimated_mprotein_values, linestyle='--', linewidth=2, marker='', zorder=3, color='b', label="Estimated M protein")
ax1.plot(measurement_times, Mprotein_values, linestyle='', marker='x', zorder=3, color='k', label="Observed M protein")
# Plot treatments
ax2 = ax1.twinx()
for treat_index in range(len(treatment_history)):
this_treatment = treatment_history[treat_index]
# Adaptation made to simulation study 2:
if treat_index>0:
ax1.axvline(this_treatment.start, color="k", linewidth=1, linestyle="-", label="Start of period of interest")
if this_treatment.id != 0:
treatment_duration = this_treatment.end - this_treatment.start
if this_treatment.id > maxdrugkey:
maxdrugkey = this_treatment.id
#drugs_1 = list of drugs from dictionary mapping id-->druglist, key=this_treatment.id
#for ii in range(len(drugs_1)):
# drugkey = drug_dictionary_OSLO[drugs_1[ii]]
# if drugkey > maxdrugkey:
# maxdrugkey = drugkey
# # Rectangle( x y , width , height , ...)
# ax2.add_patch(Rectangle((this_treatment.start, drugkey - plotheight/2), treatment_duration, plotheight, zorder=2, color=drug_colordict[drugkey]))
ax2.add_patch(Rectangle((this_treatment.start, this_treatment.id - plotheight/2), treatment_duration, plotheight, zorder=2, color="lightskyblue")) #color=treat_colordict[treat_line_id]))
ax1.set_title(plot_title)
ax1.set_xlabel("Days")
ax1.set_ylabel("Serum M protein (g/L)")
ax1.set_ylim(bottom=0)
ax2.set_ylabel("Treatment line. max="+str(maxdrugkey))
ax2.set_yticks(range(maxdrugkey+1))
ax2.set_yticklabels(range(maxdrugkey+1))
#ax2.set_ylim([-0.5,len(unique_drugs)+0.5]) # If you want to cover all unique drugs
ax1.set_zorder(ax1.get_zorder()+3)
ax1.legend()
#ax2.legend() # For drugs, no handles with labels found to put in legend.
fig.tight_layout()
if savename != 0:
plt.savefig(savename,dpi=300)
else:
if PLOT_ESTIMATES:
plt.savefig("./patient_truth_and_observations_with_model_fit"+plot_title+".pdf",dpi=300)
else:
plt.savefig("./patient_truth_and_observations"+plot_title+".pdf",dpi=300)
#plt.show()
plt.close()
def plot_treatment_region_with_estimate(true_parameters, patient, estimated_parameters=[], PLOT_ESTIMATES=False, plot_title="Patient 1", savename=0):
measurement_times = patient.get_measurement_times()
treatment_history = patient.get_treatment_history()
Mprotein_values = patient.get_Mprotein_values()
time_zero = min(treatment_history[0].start, measurement_times[0])
time_max = find_max_time(measurement_times)
plotting_times = np.linspace(time_zero, time_max, int((measurement_times[-1]+1)*10))
# Plot true M protein values according to true parameters
plotting_mprotein_values = measure_Mprotein_noiseless(true_parameters, plotting_times, treatment_history)
# Count resistant part
resistant_parameters = Parameters((true_parameters.Y_0*true_parameters.pi_r), 1, true_parameters.g_r, true_parameters.g_s, true_parameters.k_1, true_parameters.sigma)
plotting_resistant_mprotein_values = measure_Mprotein_noiseless(resistant_parameters, plotting_times, treatment_history)
# Plot M protein values
plotheight = 1
maxdrugkey = 0
fig, ax1 = plt.subplots()
ax1.patch.set_facecolor('none')
# Plot sensitive and resistant
if true_parameters.pi_r > 10e-10 and true_parameters.pi_r < 1-10e-10:
# Plot resistant
ax1.plot(plotting_times, plotting_resistant_mprotein_values, linestyle='-', marker='', zorder=3, color='r', label="Estimated M protein (resistant)")
# Plot total M protein
ax1.plot(plotting_times, plotting_mprotein_values, linestyle='--', marker='', zorder=3, color='k', label="Estimated M protein (total)")
elif true_parameters.pi_r > 1-10e-10:
ax1.plot(plotting_times, plotting_mprotein_values, linestyle='--', marker='', zorder=3, color='r', label="Estimated M protein (total)")
else:
ax1.plot(plotting_times, plotting_mprotein_values, linestyle='--', marker='', zorder=3, color='k', label="Estimated M protein (total)")
ax1.plot(measurement_times, Mprotein_values, linestyle='', marker='x', zorder=3, color='k', label="Observed M protein")
#[ax1.axvline(time, color="k", linewidth=0.5, linestyle="-") for time in measurement_times]
# Plot treatments
ax2 = ax1.twinx()
for treat_index in range(len(treatment_history)):
this_treatment = treatment_history[treat_index]
if this_treatment.id != 0:
treatment_duration = this_treatment.end - this_treatment.start
if this_treatment.id > maxdrugkey:
maxdrugkey = this_treatment.id
#drugs_1 = list of drugs from dictionary mapping id-->druglist, key=this_treatment.id
#for ii in range(len(drugs_1)):
# drugkey = drug_dictionary_OSLO[drugs_1[ii]]
# if drugkey > maxdrugkey:
# maxdrugkey = drugkey
# # Rectangle( x y , width , height , ...)
# ax2.add_patch(Rectangle((this_treatment.start, drugkey - plotheight/2), treatment_duration, plotheight, zorder=2, color=drug_colordict[drugkey]))
ax2.add_patch(Rectangle((this_treatment.start, this_treatment.id - plotheight/2), treatment_duration, plotheight, zorder=2, color="lightskyblue")) #color=treat_colordict[treat_line_id]))
ax1.set_title(plot_title)
ax1.set_xlabel("Days")
ax1.set_ylabel("Serum M protein (g/dL)")
ax1.set_ylim(bottom=0, top=(1.1*max(Mprotein_values)))
#ax1.set_xlim(left=time_zero)
ax2.set_ylabel("Treatment id for blue region")
ax2.set_yticks([maxdrugkey])
ax2.set_yticklabels([maxdrugkey])
ax2.set_ylim(bottom=maxdrugkey-plotheight, top=maxdrugkey+plotheight)
#ax2.set_ylim([-0.5,len(unique_drugs)+0.5]) # If you want to cover all unique drugs
ax1.set_zorder(ax1.get_zorder()+3)
ax1.legend()
#ax2.legend() # For drugs, no handles with labels found to put in legend.
fig.tight_layout()
plt.savefig(savename,dpi=300)
#plt.show()
plt.close()
def plot_to_compare_estimated_and_predicted_drug_dynamics(true_parameters, predicted_parameters, patient, estimated_parameters=[], PLOT_ESTIMATES=False, plot_title="Patient 1", savename=0):
measurement_times = patient.get_measurement_times()
treatment_history = patient.get_treatment_history()
Mprotein_values = patient.get_Mprotein_values()
time_zero = min(treatment_history[0].start, measurement_times[0])
time_max = find_max_time(measurement_times)
plotting_times = np.linspace(time_zero, time_max, int((measurement_times[-1]+1)*10))
# Plot true M protein values according to true parameters
plotting_mprotein_values = measure_Mprotein_noiseless(true_parameters, plotting_times, treatment_history)
# Count resistant part
resistant_parameters = Parameters((true_parameters.Y_0*true_parameters.pi_r), 1, true_parameters.g_r, true_parameters.g_s, true_parameters.k_1, true_parameters.sigma)
plotting_resistant_mprotein_values = measure_Mprotein_noiseless(resistant_parameters, plotting_times, treatment_history)
# Plot predicted M protein values according to predicted parameters
plotting_mprotein_values_pred = measure_Mprotein_noiseless(predicted_parameters, plotting_times, treatment_history)
# Count resistant part
resistant_parameters_pred = Parameters((predicted_parameters.Y_0*predicted_parameters.pi_r), 1, predicted_parameters.g_r, predicted_parameters.g_s, predicted_parameters.k_1, predicted_parameters.sigma)
plotting_resistant_mprotein_values_pred = measure_Mprotein_noiseless(resistant_parameters_pred, plotting_times, treatment_history)
# Plot M protein values
plotheight = 1
maxdrugkey = 2
fig, ax1 = plt.subplots()
ax1.patch.set_facecolor('none')
# Plot sensitive and resistant
ax1.plot(plotting_times, plotting_resistant_mprotein_values, linestyle='-', marker='', zorder=3, color='r', label="Estimated M protein (resistant)")
# Plot sensitive and resistant
ax1.plot(plotting_times, plotting_resistant_mprotein_values_pred, linestyle='--', marker='', zorder=3, color='orange', label="Predicted M protein (resistant)")
# Plot total M protein
ax1.plot(plotting_times, plotting_mprotein_values, linestyle='--', marker='', zorder=3, color='k', label="Estimated M protein (total)")
# Plot total M protein, predicted
ax1.plot(plotting_times, plotting_mprotein_values_pred, linestyle='--', marker='', zorder=3, color='b', label="Predicted M protein (total)")
ax1.plot(measurement_times, Mprotein_values, linestyle='', marker='x', zorder=3, color='k', label="Observed M protein")
[ax1.axvline(time, color="k", linewidth=0.5, linestyle="-") for time in measurement_times]
# Plot treatments
ax2 = ax1.twinx()
for treat_index in range(len(treatment_history)):
this_treatment = treatment_history[treat_index]
if this_treatment.id != 0:
treatment_duration = this_treatment.end - this_treatment.start
if this_treatment.id > maxdrugkey:
maxdrugkey = this_treatment.id
#drugs_1 = list of drugs from dictionary mapping id-->druglist, key=this_treatment.id
#for ii in range(len(drugs_1)):
# drugkey = drug_dictionary_OSLO[drugs_1[ii]]
# if drugkey > maxdrugkey:
# maxdrugkey = drugkey
# # Rectangle( x y , width , height , ...)
# ax2.add_patch(Rectangle((this_treatment.start, drugkey - plotheight/2), treatment_duration, plotheight, zorder=2, color=drug_colordict[drugkey]))
ax2.add_patch(Rectangle((this_treatment.start, this_treatment.id - plotheight/2), treatment_duration, plotheight, zorder=2, color="lightskyblue")) #color=treat_colordict[treat_line_id]))
ax1.set_title(plot_title)
ax1.set_xlabel("Days")
ax1.set_ylabel("Serum M protein (g/dL)")
ax1.set_ylim(bottom=0, top=(1.1*max(Mprotein_values)))
#ax1.set_xlim(left=time_zero)
ax2.set_ylabel("Treatment line. max="+str(maxdrugkey))
ax2.set_yticks(range(maxdrugkey+1))
ax2.set_yticklabels(range(maxdrugkey+1))
ax2.set_ylim(bottom=0, top=maxdrugkey+plotheight/2)
#ax2.set_ylim([-0.5,len(unique_drugs)+0.5]) # If you want to cover all unique drugs
ax1.set_zorder(ax1.get_zorder()+3)
ax1.legend()
ax2.legend()
fig.tight_layout()
plt.savefig(savename,dpi=300)
#plt.show()
plt.close()
# Plot posterior confidence intervals
def plot_posterior_confidence_intervals(training_instance_id, patient, sorted_pred_y_values, parameter_estimates=[], PLOT_POINT_ESTIMATES=False, PLOT_TREATMENTS=False, plot_title="", savename="0", y_resolution=1000, n_chains=4, n_samples=1000):
measurement_times = patient.get_measurement_times()
treatment_history = patient.get_treatment_history()
Mprotein_values = patient.get_Mprotein_values()
time_zero = min(treatment_history[0].start, measurement_times[0])
time_max = find_max_time(measurement_times)
plotting_times = np.linspace(time_zero, time_max, y_resolution)
fig, ax1 = plt.subplots()
ax1.patch.set_facecolor('none')
if PLOT_POINT_ESTIMATES:
# Plot true M protein values according to parameter estimates
plotting_mprotein_values = measure_Mprotein_noiseless(parameter_estimates, plotting_times, treatment_history)
# Count resistant part
resistant_parameters = Parameters((parameter_estimates.Y_0*parameter_estimates.pi_r), 1, parameter_estimates.g_r, parameter_estimates.g_s, parameter_estimates.k_1, parameter_estimates.sigma)
plotting_resistant_mprotein_values = measure_Mprotein_noiseless(resistant_parameters, plotting_times, treatment_history)
# Plot resistant M protein
ax1.plot(plotting_times, plotting_resistant_mprotein_values, linestyle='-', marker='', zorder=3, color='r', label="Estimated M protein (resistant)")
# Plot total M protein
ax1.plot(plotting_times, plotting_mprotein_values, linestyle='--', marker='', zorder=3, color='k', label="Estimated M protein (total)")
# Plot posterior confidence intervals
# 95 % empirical confidence interval
color_array = ["#fbd1b4", "#f89856", "#e36209"] #["#fbd1b4", "#fab858", "#f89856", "#f67c27", "#e36209"] #https://icolorpalette.com/color/rust-orange
for index, critical_value in enumerate([0.05, 0.25, 0.45]): # Corresponding to confidence levels 90, 50, and 10
# Get index to find right value
lower_index = int(critical_value*sorted_pred_y_values.shape[0]) #n_chains*n_samples)
upper_index = int((1-critical_value)*sorted_pred_y_values.shape[0]) #n_chains*n_samples)
# index at intervals to get 95 % limit value
lower_limits = sorted_pred_y_values[lower_index,training_instance_id,:]
upper_limits = sorted_pred_y_values[upper_index,training_instance_id,:] #color=color_array[index]
ax1.fill_between(plotting_times, lower_limits, upper_limits, color=plt.cm.copper(1-critical_value), label='%3.0f %% confidence band on M protein value' % (100*(1-2*critical_value)))
# Plot M protein observations
ax1.plot(measurement_times, Mprotein_values, linestyle='', marker='x', zorder=3, color='k', label="Observed M protein") #[ax1.axvline(time, color="k", linewidth=0.5, linestyle="-") for time in measurement_times]
# Plot treatments
if PLOT_TREATMENTS:
plotheight = 1
maxdrugkey = 0
ax2 = ax1.twinx()
for treat_index in range(len(treatment_history)):
this_treatment = treatment_history[treat_index]
if this_treatment.id != 0:
treatment_duration = this_treatment.end - this_treatment.start
if this_treatment.id > maxdrugkey:
maxdrugkey = this_treatment.id
ax2.add_patch(Rectangle((this_treatment.start, this_treatment.id - plotheight/2), treatment_duration, plotheight, zorder=2, color="lightskyblue")) #color=treat_colordict[treat_line_id]))
ax1.set_title(plot_title)
ax1.set_xlabel("Days")
ax1.set_ylabel("Serum M protein (g/dL)")
ax1.set_ylim(bottom=0, top=(1.1*max(Mprotein_values)))
#ax1.set_xlim(left=time_zero)
if PLOT_TREATMENTS:
ax2.set_ylabel("Treatment id for blue region")
ax2.set_yticks([maxdrugkey])
ax2.set_yticklabels([maxdrugkey])
ax2.set_ylim(bottom=maxdrugkey-plotheight, top=maxdrugkey+plotheight)
#ax2.set_ylim([-0.5,len(unique_drugs)+0.5]) # If you want to cover all unique drugs
ax1.set_zorder(ax1.get_zorder()+3)
ax1.legend()
#ax2.legend() # For drugs, no handles with labels found to put in legend.
fig.tight_layout()
plt.savefig(savename,dpi=300)
#plt.show()
plt.close()
def plot_posterior_local_confidence_intervals(ii, patient, sorted_local_pred_y_values, parameters=[], PLOT_PARAMETERS=False, PLOT_TREATMENTS=False, plot_title="", savename="0", y_resolution=1000, n_chains=4, n_samples=1000, sorted_resistant_mprotein=[], PLOT_MEASUREMENTS = True, PLOT_RESISTANT=True, IS_TEST_PATIENT=False, CLIP_MPROTEIN_TIME=0, clinic_view=False, p_progression=[], time_scale=1, M_scale=1, plot_pfs=False, plot_KapLam=False, print_p_progression=False):
Mprotein_values = patient.get_Mprotein_values() * M_scale
measurement_times = patient.get_measurement_times() * time_scale
######
# Scale back
patient.Mprotein_values = patient.Mprotein_values * M_scale
patient.measurement_times = patient.measurement_times * time_scale
for covariate_name, time_series in patient.longitudinal_data.items():
patient.longitudinal_times[covariate_name] = patient.longitudinal_times[covariate_name] * time_scale
######
if clinic_view:
treatment_history = np.array([Treatment(start=1, end=CLIP_MPROTEIN_TIME+6*28, id=1)])
time_max = CLIP_MPROTEIN_TIME+6*28
else:
treatment_history = patient.get_treatment_history()
time_max = find_max_time(measurement_times)
time_zero = min(treatment_history[0].start, measurement_times[0])
plotting_times = np.linspace(time_zero, time_max, y_resolution)
fig, ax1 = plt.subplots()
ax1.patch.set_facecolor('none')
if IS_TEST_PATIENT:
ax1.axvline(CLIP_MPROTEIN_TIME, color="k", linewidth=1, linestyle="-", zorder=3.9)
# Plot posterior confidence intervals for Resistant M protein
# 95 % empirical confidence interval
if PLOT_RESISTANT:
if len(sorted_resistant_mprotein) > 0:
for index, critical_value in enumerate([0.05, 0.25, 0.45]): # Corresponding to confidence levels 90, 50, and 10
# Get index to find right value
lower_index = int(critical_value*sorted_resistant_mprotein.shape[0]) #n_chains*n_samples)
upper_index = int((1-critical_value)*sorted_resistant_mprotein.shape[0]) #n_chains*n_samples)
# index at intervals to get 95 % limit value
lower_limits = sorted_resistant_mprotein[lower_index,:]
upper_limits = sorted_resistant_mprotein[upper_index,:]
ax1.fill_between(plotting_times, lower_limits, upper_limits, color=plt.cm.copper(1-critical_value), label='%3.0f %% CI, resistant M protein' % (100*(1-2*critical_value)), zorder=0+index*0.1)
# Plot posterior confidence intervals for total M protein
# 95 % empirical confidence interval
color_array = ["#fbd1b4", "#f89856", "#e36209"] #["#fbd1b4", "#fab858", "#f89856", "#f67c27", "#e36209"] #https://icolorpalette.com/color/rust-orange
for index, critical_value in enumerate([0.05, 0.25, 0.45]): # Corresponding to confidence levels 90, 50, and 10
# Get index to find right value
lower_index = int(critical_value*sorted_local_pred_y_values.shape[0]) #n_chains*n_samples)
upper_index = int((1-critical_value)*sorted_local_pred_y_values.shape[0]) #n_chains*n_samples)
# index at intervals to get 95 % limit value
lower_limits = sorted_local_pred_y_values[lower_index,:]
upper_limits = sorted_local_pred_y_values[upper_index,:]
shade_array = [0.7, 0.5, 0.35]
ax1.fill_between(plotting_times, lower_limits, upper_limits, color=plt.cm.bone(shade_array[index]), label='%3.0f %% CI, total M protein' % (100*(1-2*critical_value)), zorder=1+index*0.1)
if PLOT_PARAMETERS:
# Plot true M protein curves according to parameters
plotting_mprotein_values = measure_Mprotein_noiseless(parameters, plotting_times, treatment_history)
# Count resistant part
resistant_parameters = Parameters((parameters.Y_0*parameters.pi_r), 1, parameters.g_r, parameters.g_s, parameters.k_1, parameters.sigma)
plotting_resistant_mprotein_values = measure_Mprotein_noiseless(resistant_parameters, plotting_times, treatment_history)
# Plot resistant M protein
if PLOT_RESISTANT:
ax1.plot(plotting_times, plotting_resistant_mprotein_values, linestyle='--', marker='', zorder=2.9, color=plt.cm.hot(0.2), label="True M protein (resistant)")
# Plot total M protein
ax1.plot(plotting_times, plotting_mprotein_values, linestyle='--', marker='', zorder=3, color='cyan', label="True M protein (total)")
# Plot M protein observations
if PLOT_MEASUREMENTS == True:
if IS_TEST_PATIENT:
ax1.plot(measurement_times[measurement_times<=CLIP_MPROTEIN_TIME], Mprotein_values[measurement_times<=CLIP_MPROTEIN_TIME], linestyle='', marker='x', zorder=4, color='k', label="Observed M protein")
if not clinic_view:
# plot the unseen observations
ax1.plot(measurement_times[measurement_times>CLIP_MPROTEIN_TIME], Mprotein_values[measurement_times>CLIP_MPROTEIN_TIME], linestyle='', markersize=6, markeredgewidth=1.7, marker='x', zorder=3.99, color='k', label="Unobserved M protein")
ax1.plot(measurement_times[measurement_times>CLIP_MPROTEIN_TIME], Mprotein_values[measurement_times>CLIP_MPROTEIN_TIME], linestyle='', markersize=5.5, markeredgewidth=1, marker='x', zorder=4, color='whitesmoke', label="Unobserved M protein")
else:
ax1.plot(measurement_times, Mprotein_values, linestyle='', marker='x', zorder=4, color='k', label="Observed M protein") #[ax1.axvline(time, color="k", linewidth=0.5, linestyle="-") for time in measurement_times]
# Plot treatments
if PLOT_TREATMENTS:
plotheight = 1
maxdrugkey = 0
ax2 = ax1.twinx()
for treat_index in range(len(treatment_history)):
this_treatment = treatment_history[treat_index]
if this_treatment.id != 0:
treatment_duration = this_treatment.end - this_treatment.start
if this_treatment.id > maxdrugkey:
maxdrugkey = this_treatment.id
ax2.add_patch(Rectangle((this_treatment.start, this_treatment.id - plotheight/2), treatment_duration, plotheight, zorder=0, color="lightskyblue")) #color=treat_colordict[treat_line_id]))
if plot_pfs == True and not clinic_view:
ax1.axvline(patient.pfs, color="r", linewidth=1, linestyle="--", label="PFS") # This was never scaled
if plot_KapLam:
ax3 = ax1.twinx()
ax4 = ax1.twinx()
try:
Kappa_values = patient.longitudinal_data["Kappa Light Chain, Free"]
Kappa_times = patient.longitudinal_times["Kappa Light Chain, Free"]
except:
Kappa_values = np.array([])
Kappa_times = np.array([])
try:
Lambda_values = patient.longitudinal_data["Lambda Light Chain, Free"]
Lambda_times = patient.longitudinal_times["Lambda Light Chain, Free"]
except:
Lambda_values = np.array([])
Lambda_times = np.array([])
try:
new_ratio_values = patient.longitudinal_data["Kappa Lt Chain,Free/Lambda Lt Chain,Free"]
new_ratio_times = patient.longitudinal_times["Kappa Lt Chain,Free/Lambda Lt Chain,Free"]
except:
new_ratio_values = np.array([])
new_ratio_times = np.array([])
if clinic_view:
before_clip_mask = Kappa_times <= CLIP_MPROTEIN_TIME
ax3.plot(Kappa_times[before_clip_mask], Kappa_values[before_clip_mask], linestyle='-', marker='x', zorder=2.1, color=plt.cm.viridis(0.9), label="Kappa Light Chain SDTM")
before_clip_mask = Lambda_times <= CLIP_MPROTEIN_TIME
ax4.plot(Lambda_times[before_clip_mask], Lambda_values[before_clip_mask], linestyle='-', marker='x', zorder=2.1, color=plt.cm.viridis(1.0), label="Lambda Light Chain SDTM")
before_clip_mask = Lambda_times <= CLIP_MPROTEIN_TIME
ax1.plot(new_ratio_times[before_clip_mask], new_ratio_values[before_clip_mask], linestyle='--', marker='x', zorder=2.1, color=plt.cm.viridis(0.8), label="Kappa/Lambda ratio SDTM")
before_clip_mask = patient.longitudinal_times["Kappa Lt Chain,Free/Lambda Lt Chain,Free (RATIO)"] <= CLIP_MPROTEIN_TIME
ax1.plot(patient.longitudinal_times["Kappa Lt Chain,Free/Lambda Lt Chain,Free (RATIO)"][before_clip_mask], patient.longitudinal_data["Kappa Lt Chain,Free/Lambda Lt Chain,Free (RATIO)"][before_clip_mask], linestyle='-', marker='x', zorder=2, color='g', label="Kappa/Lambda ratio")
plot_title = plot_title + " : " + patient.name
else:
#ax1.plot(measurement_times, patient.KappaLambdaRatio, linestyle='-', marker='x', zorder=2, color='g', label="Kappa/Lambda ratio")
ax3.plot(Kappa_times, Kappa_values, linestyle='-', marker='x', zorder=2.1, color=plt.cm.viridis(0.9), label="Kappa Light Chain SDTM")
ax4.plot(Lambda_times, Lambda_values, linestyle='-', marker='x', zorder=2.1, color=plt.cm.viridis(1.0), label="Lambda Light Chain SDTM")
ax1.plot(new_ratio_times, new_ratio_values, linestyle='--', marker='x', zorder=2.1, color=plt.cm.viridis(0.8), label="Kappa/Lambda ratio SDTM")
ax1.plot(patient.longitudinal_times["Kappa Lt Chain,Free/Lambda Lt Chain,Free (RATIO)"], patient.longitudinal_data["Kappa Lt Chain,Free/Lambda Lt Chain,Free (RATIO)"], linestyle='-', marker='x', zorder=2, color='g', label="Kappa/Lambda ratio")
plot_title = plot_title + " : " + patient.name
if print_p_progression:
plot_title = plot_title + "\nP(progress within 6 cycles) = " + str(p_progression[ii - 137])
ax1.set_title(plot_title)
if clinic_view:
latest_cycle_start = int(np.rint( ((CLIP_MPROTEIN_TIME+6*28) - 1) // 28 + 1 ))
else:
latest_cycle_start = int(np.rint( (max(measurement_times) - 1) // 28 + 1 ))
tick_labels = [1] + [cs for cs in range(6, latest_cycle_start+1, 6)]
#step_size = 6
##while len(tick_labels) < min(9, latest_cycle_start):
## step_size = step_size - 1
## tick_labels = [1] + [cs for cs in range(1 + step_size, latest_cycle_start, step_size)]
#if len(tick_labels) < 4:
# step_size = 1
# tick_labels = [1] + [cs for cs in range(1 + step_size, latest_cycle_start, step_size)] + [latest_cycle_start]
if len(tick_labels) < 2:
tick_labels = [1, latest_cycle_start]
tick_positions = [(cycle_nr - 1) * 28 + 1 for cycle_nr in tick_labels]
ax1.set_xticks(tick_positions, tick_labels)
ax1.set_xlabel("Cycles")
if clinic_view:
ax1.set_xlim(right=CLIP_MPROTEIN_TIME + 6*28)
#cycle_data = [(mtime - 1) // 28 + 1 for mtime in measurement_times]
#num_ticks = min(len(cycle_data), 7)
#step_size = len(cycle_data) // num_ticks
#tick_positions = measurement_times[::step_size]
#tick_labels = cycle_data[::step_size]
#tick_labels = [int(label) for label in tick_labels]
#ax1.set_xticks(measurement_times, cycle_data)
#tick_positions = measurement_times[1::28]
#cycles = [xx for xx in tick_positions]
#ax1.set_xticks(tick_positions, cycles)
#ax1.set_xlabel("Days")
ax1.set_ylabel("Serum M protein (g/L)")
ax1.set_ylim(bottom=0, top=(1.1*max(Mprotein_values)))
if plot_KapLam:
ax3.set_ylabel("Kappa Light Chain, Free")
ax3.set_ylim(bottom=0, top=((1.1*max(Kappa_values)) if len(Kappa_values)>1 else 1))
ax4.set_ylabel("Lambda Light Chain, Free")
ax4.set_ylim(bottom=0, top=((1.1*max(Lambda_values)) if len(Lambda_values)>1 else 1))
#ax1.set_xlim(left=time_zero)
if PLOT_TREATMENTS:
ax2.set_ylabel("Treatment id for blue region")
ax2.set_yticks([maxdrugkey])
ax2.set_yticklabels([maxdrugkey])
ax2.set_ylim(bottom=maxdrugkey-plotheight, top=maxdrugkey+plotheight)
#ax2.set_ylim([-0.5,len(unique_drugs)+0.5]) # If you want to cover all unique drugs
ax1.set_zorder(ax1.get_zorder()+3)
if plot_KapLam:
ax3.set_zorder(ax1.get_zorder()+1)
ax4.set_zorder(ax1.get_zorder()+2)
#handles, labels = ax1.get_legend_handles_labels()
#lgd = ax1.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5,-0.1))
#ax1.legend()
#ax2.legend() # For drugs, no handles with labels found to put in legend.
fig.tight_layout()
plt.savefig(savename, dpi=300) #, bbox_extra_artists=(lgd), bbox_inches='tight')
#plt.show()
plt.close()
def plot_posterior_traces(idata, SAVEDIR, name, psi_prior, model_name, patientwise=True, net_list=["rho_s", "rho_r", "pi_r"], INFERENCE_MODE="Full"):
if model_name == "linear":
print("Plotting posterior/trace plots")
# Autocorrelation plots:
az.plot_autocorr(idata, var_names=["sigma_obs"])
plt.close()
az.plot_trace(idata, var_names=('alpha', 'beta_rho_r', 'beta_pi_r', 'omega', 'sigma_obs'), combined=True)
plt.tight_layout()