-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackup_4_updated_ct_script.py
executable file
·486 lines (349 loc) · 19 KB
/
backup_4_updated_ct_script.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
from subprocess import call
import json
import datetime
#from datetime import datetime,timedelta
import time
import os
from matplotlib import pyplot as plt
openaps_rate = []
wrapper_rate = []
running_temp = []
track_increase = {"iteration": 0, "num_of_increase":0}
track_decrease = {"iteration": 0, "num_of_decrease":0}
gt_target_visit_stat = 0
lt_target_rising_visit_stat = 0
lt_target_falling_visit_stat = 0
init_ebg_pointer = 0
fault_occurrence = 0
#Input to the algo_bw.js. algo_bw.js format all the info and send to glucosym server. An algorithm is running in glucosym server that calculated next glucose and send the value back.
algo_input_list = {"index":0,"BGTarget":95,"sens":45,"deltat_v":20,"dia":4,"dt":5.0,"time":6000,"bioavail":6.0,"Vg":253.0,"IRss":1.3,"events":{"bolus":[{ "amt": 0.0, "start":0}],"basal":[{ "amt":0, "start":0,"length":0}],"carb":[{"amt":0.0,"start":0,"length":0},{"amt":0.0,"start":0,"length":0}]}}
#write the algo_input_list to a file named algo_input.json so that algo_bw.js can read the input from that file
with open("../glucosym/closed_loop_algorithm_samples/algo_input.json", "w") as write_algo_input_init:
json.dump(algo_input_list, write_algo_input_init, indent=4)
write_algo_input_init.close()
suggested_data_to_dump = {}
list_suggested_data_to_dump = []
iteration_num = 140
#record the time 5 minutes ago, we need this time to attach with the recent glucose value
#time_5_minutes_back = ((time.time())*1000)-3000
for _ in range(iteration_num):
with open("../glucosym/closed_loop_algorithm_samples/algo_input.json") as update_algo_input:
loaded_algo_input = json.load(update_algo_input)
update_algo_input.close()
loaded_algo_input_copy = loaded_algo_input.copy()
loaded_algo_input_copy['index'] = _
#print(loaded_algo_input_copy)
with open("monitor/glucose.json") as f:
data = json.load(f)
f.close()
data_to_prepend = data[0].copy()
read_glucose_from_glucosym = open("../glucosym/closed_loop_algorithm_samples/glucose_output_algo_bw.txt", "r")
loaded_glucose = read_glucose_from_glucosym.read()
data_to_prepend["glucose"] = loaded_glucose
data_to_prepend["date"] = int(time.time())*1000
data.insert(0, data_to_prepend)
with open('monitor/glucose.json', 'w') as outfile:
json.dump(data, outfile, indent=4)
outfile.close()
#current_timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%dT%H:%M:%S-07:00')
#with open('monitor/clock.json','w') as update_clock:
# json.dump(current_timestamp, update_clock)
##For the very first time get the time of 5 minutes ago from now and set it to the first glucose data
#if _==0:
# call("date -Ins -s $(date -Ins -d '-5 minute')", shell=True)
# first_glucose_to_prepend = data[0].copy()
# first_glucose_to_prepend["date"]=int(time.time())*1000
# print(data[0])
# print(data[0]["date"])
# with open("monitor/glucose.json", "w") as dump_first_glucose:
# json.dump(data[0], dump_first_glucose, indent=4)
# dump_first_glucose.close()
# #print(data_to_prepend["date"])
call("date -Ins -s $(date -Ins -d '+5 minute')", shell=True)
current_timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%dT%H:%M:%S-07:00')
with open('monitor/clock.json','w') as update_clock:
json.dump(current_timestamp, update_clock)
call(["openaps", "report", "invoke", "settings/profile.json"])
call(["openaps", "report", "invoke", "monitor/iob.json"])
#run openaps to get suggested tempbasal
call(["openaps", "report", "invoke", "enact/suggested.json"])
# current_timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%dT%H:%M:%S-07:00')
#read the output in suggested.json and append it to list_suggested_data_to_dump list. Basically we are trying to get all the suggest ed data and dump make a list lf that and then dump it to all_suggested.json file
with open("enact/suggested.json") as read_suggested:
loaded_suggested_data = json.load(read_suggested)
#list_suggested_data_to_dump.insert(0,loaded_suggested_data)
#list_suggested_data_to_dump.append(loaded_suggested_data)
read_suggested.close()
#################################### Context table check #################################################################
bg_target = 110
if "eventualBG" in loaded_suggested_data:
e_bg = loaded_suggested_data["eventualBG"]
glucose = float(loaded_glucose)
running_temp_rate = loaded_suggested_data["running_temp"]["rate"]
basal = loaded_suggested_data["basal"]
if glucose < 39:
init_ebg_pointer = 0
else:
init_ebg_pointer = init_ebg_pointer + 1
if _ == 0 and glucose >= 39:
prev_e_bg = e_bg
elif init_ebg_pointer == 1:
prev_e_bg = e_bg
# if "short_avgdelta" in loaded_suggested_data:
# short_avgdelta = loaded_suggested_data["short_avgdelta"]
# if "bgi" in loaded_suggested_data:
# bgi = loaded_suggested_data["bgi"]
################# Context table first row ########################
if glucose < 39:
if running_temp_rate >= basal:
if loaded_suggested_data["rate"] == 0 and loaded_suggested_data["duration"] == 0 :
print("\nNO Fault\n")
else:
print("\n***************************************")
print("********** Faultiy !!!!! *************")
print("Glucose < 39, Cancel_temp was not provided")
print("***************************************\n")
fault_occurrence += 1
################# Context table second row ########################
elif glucose >=39 and glucose < 75:
if loaded_suggested_data["rate"] == 0 or loaded_suggested_data["rate"] == basal:
print("\n NO fault\n")
else:
loaded_suggested_data["fault"] = "yes"
loaded_suggested_data["fault_reason"] = "Reason: 39 =< glucose <75; recommended rate is not equal to 0 or basal"
print("\n***************************************")
print("********** Faultiy !!!!! *************")
print("Reason: 39 =< glucose <=75; recommended rate is not equal to 0 or basal")
print("***************************************\n")
fault_occurrence += 1
################# Context table third row (if E_BG is above BG_Target) ########################
elif glucose >= 75:
recommended_change_rate = loaded_suggested_data["rate"] - running_temp_rate
if e_bg > bg_target:
if e_bg - prev_e_bg > 0:
if recommended_change_rate >= 0 or loaded_suggested_data["rate"] == basal:
print("\nNO Fault\n")
else:
loaded_suggested_data["fault"] = "yes"
loaded_suggested_data["fault_reason"] = "Reason: glucose > threshold(75); e_bg > bg_target; e_bg is rising; recommended_rate decreases"
print("\n***************************************")
print("********** Faultiy !!!!! *************")
print("Reason: glucose > threshhold(75); e_bg > bg_target; e_bg is rising; recommended_rate decreases")
print("***************************************\n")
fault_occurrence += 1
################# Context table fourth and fifth row ########################
elif e_bg < bg_target:
if e_bg - prev_e_bg > 0:
# lt_target_rising_visit_stat = 0
if recommended_change_rate < 0:
loaded_suggested_data["fault"] = "yes"
loaded_suggested_data["fault_reason"] = "e_bg > 75; e_bg < bg_target; bg is rising; rate decreases, but it should not decrease"
print("\n***************************************")
print("********** Faultiy !!!!! *************")
print("Reason: e_bg > 75; e_bg < bg_target; bg is rising; rate should not decrease, but it decrease twice")
print("***************************************\n")
fault_occurrence += 1
else:
print("\nNO Fault\n")
elif e_bg - prev_e_bg < 0:
# lt_target_rising_visit_stat = 0
if recommended_change_rate > 0:
loaded_suggested_data["fault"] = "yes"
loaded_suggested_data["fault_reason"] = "e_bg > 75; e_bg < bg_target and rising; rate should not decrease "
print("\n***************************************")
print("********** Faultiy !!!!! *************")
print("Reason: e_bg > 75; e_bg < bg_target and rising; rate should not decrease")
print("***************************************\n")
fault_occurrence += 1
else:
print("\nNO Fault\n")
elif e_bg - prev_e_bg == 0:
if recommended_change_rate > 0:
loaded_suggested_data["fault"] = "yes"
loaded_suggested_data["fault_reason"] = "e_bg > 75; e_bg < bg_target; neither rising nor falling; rate should not increase"
print("\n***************************************")
print("********** Faultiy !!!!! *************")
print("Reason:e_bg > 75; e_bg < bg_target; neither rising nor falling; rate should not increase")
print("***************************************\n")
fault_occurrence += 1
else:
print("\nNO Fault\n")
print("\nprev_e_bg: ", prev_e_bg)
print("e_bg: ", e_bg,"\n")
if glucose >= 39:
prev_e_bg = e_bg
list_suggested_data_to_dump.insert(0,loaded_suggested_data)
#read the output in suggested.json and append it to list_suggested_data_to_dump list. Basically we are trying to get all the suggest ed data and dump make a list lf that and then dump it to all_suggested.json file
# with open("enact/suggested.json") as read_suggested:
# loaded_suggested_data = json.load(read_suggested)
# list_suggested_data_to_dump.insert(0,loaded_suggested_data)
# #list_suggested_data_to_dump.append(loaded_suggested_data)
# read_suggested.close()
#################### Update pumphistory at very begining ##################
if _==0:
if 'duration' in loaded_suggested_data.keys():
with open("monitor/pumphistory.json") as read_pump_history:
loaded_pump_history = json.load(read_pump_history) # read whole pump_history.json
pump_history_0 = loaded_pump_history[0].copy() #load first element
pump_history_1 = loaded_pump_history[1].copy() #load second element, fist and second are both for one temp basal
pump_history_0['duration (min)'] = loaded_suggested_data['duration'] #update the values
pump_history_1['rate'] = loaded_suggested_data['rate']
pump_history_0['timestamp'] = current_timestamp
pump_history_1['timestamp'] = current_timestamp
loaded_pump_history.insert(0, pump_history_1) # insert second element back to whatever we loaded from pumphistory
loaded_pump_history.insert(0, pump_history_0) #insert first element back to whatever we loaded from pumphistory
read_pump_history.close();
with open("monitor/pumphistory.json", "w") as write_pump_history:
json.dump(loaded_pump_history, write_pump_history, indent=4)
################ Update temp_basal.json with the current temp_basal rate and duration ####################
#load temp_basal.json
with open("monitor/temp_basal.json") as read_temp_basal:
loaded_temp_basal = json.load(read_temp_basal)
loaded_temp_basal['duration']-=5
if loaded_temp_basal['duration']<=0:
loaded_temp_basal['duration'] = 0
if "doing nothing" not in loaded_suggested_data['reason']:
if loaded_temp_basal['duration']==0:
loaded_temp_basal['duration'] = loaded_suggested_data['duration']
loaded_temp_basal['rate'] = loaded_suggested_data['rate']
######################### Update input of glucosym based on new temp ##############
if loaded_suggested_data['rate'] == 0 and loaded_suggested_data['duration'] == 0:
loaded_algo_input_copy["events"]['basal'][0]['amt'] = loaded_suggested_data['basal']
loaded_algo_input_copy["events"]['basal'][0]['length'] = 30
loaded_algo_input_copy["events"]['basal'][0]['start'] = _*5
else:
loaded_algo_input_copy["events"]['basal'][0]['amt'] = loaded_suggested_data['rate']
loaded_algo_input_copy["events"]['basal'][0]['length'] = loaded_suggested_data['duration']
loaded_algo_input_copy["events"]['basal'][0]['start'] = _*5
##################### Uppdate Pupmphistory ####################################
with open("monitor/pumphistory.json") as read_pump_history:
loaded_pump_history = json.load(read_pump_history) # read whole pump_history.json
pump_history_0 = loaded_pump_history[0].copy() #load first element
pump_history_1 = loaded_pump_history[1].copy() #load second element, fist and second are both for one temp basal
pump_history_0['duration (min)'] = loaded_suggested_data['duration'] #update the values
pump_history_1['rate'] = loaded_suggested_data['rate']
pump_history_0['timestamp'] = current_timestamp
pump_history_1['timestamp'] = current_timestamp
loaded_pump_history.insert(0, pump_history_1) # insert second element back to whatever we loaded from pumphistory
loaded_pump_history.insert(0, pump_history_0) #insert first element back to whatever we loaded from pumphistory
read_pump_history.close();
with open("monitor/pumphistory.json", "w") as write_pump_history:
json.dump(loaded_pump_history, write_pump_history, indent=4)
else:
if loaded_temp_basal['rate']!=loaded_suggested_data['rate']:
loaded_temp_basal['rate']=loaded_suggested_data['rate']
loaded_temp_basal['duration']=loaded_suggested_data['duration']
####################### Update input of glucosym based on new temp ###########
loaded_algo_input_copy["events"]['basal'][0]['amt'] = loaded_suggested_data['rate']
loaded_algo_input_copy["events"]['basal'][0]['length'] = loaded_suggested_data['duration']
loaded_algo_input_copy["events"]['basal'][0]['start'] = _*5
#################### Uppdate Pumphistory ############################
with open("monitor/pumphistory.json") as read_pump_history:
loaded_pump_history = json.load(read_pump_history) # read whole pump_history.json
pump_history_0 = loaded_pump_history[0].copy() #load first element
pump_history_1 = loaded_pump_history[1].copy() #load second element, fist and second are both for one temp basal
pump_history_0['duration (min)'] = loaded_suggested_data['duration'] #update the values
pump_history_1['rate'] = loaded_suggested_data['rate']
pump_history_0['timestamp'] = current_timestamp
pump_history_1['timestamp'] = current_timestamp
loaded_pump_history.insert(0, pump_history_1) # insert second element back to whatever we loaded from pumphistory
loaded_pump_history.insert(0, pump_history_0) #insert first element back to whatever we loaded from pumphistory
read_pump_history.close();
with open("monitor/pumphistory.json", "w") as write_pump_history:
json.dump(loaded_pump_history, write_pump_history, indent=4)
# else:
# if loaded_temp_basal['duration']<=0:
# loaded_temp_basal['duration'] = 0
read_temp_basal.close()
#print(loaded_algo_input_copy)
# if loaded_temp_basal['duration']<=0:
# if 'duration' in loaded_suggested_data:
# loaded_temp_basal['duration'] = loaded_suggested_data['duration']
# loaded_temp_basal['rate'] = loaded_suggested_data['rate']
# read_temp_basal.close()
#if loaded_temp_basal['duration']<=0:
# loaded_temp_basal['duration']=0
# if 'rate' in loaded_suggested_data.keys():
# loaded_temp_basal['duration'] = loaded_suggested_data['duration']
# loaded_temp_basal['rate'] = loaded_suggested_data['rate']
# read_temp_basal.close()
#if "no temp required" in loaded_suggested_data['reason']:
# loaded_temp_basal['duration'] = loaded_temp_basal['duration']
# loaded_temp_basal['rate'] = loaded_temp_basal['rate']
with open("monitor/temp_basal.json", "w") as write_temp_basal:
json.dump(loaded_temp_basal, write_temp_basal, indent=4)
#print(suggested_data_to_dump)
#write the list_suggested_data_to_dump into all_suggested.json file
with open("enact/all_suggested.json", "w") as dump_suggested:
json.dump(list_suggested_data_to_dump, dump_suggested, indent=4)
dump_suggested.close()
#if 'rate' in loaded_suggested_data.keys():
#update the insulin parameter input of glucosym. This insulin parameters is received from openaps(suggested.json)
# algo_input_list["events"]['basal'][0]['amt'] = loaded_suggested_data['rate']
# algo_input_list["events"]['basal'][0]['length'] = loaded_suggested_data['duration']
# algo_input_list["events"]['basal'][0]['start'] = _*5
#os.chdir("../glucosym/closed_loop_algorithm_samples")
####################### Write algo_input having the suggested output from openaps ##########################
with open("../glucosym/closed_loop_algorithm_samples/algo_input.json", "w") as write_algo_input:
json.dump(loaded_algo_input_copy, write_algo_input, indent=4)
call(["node", "../glucosym/closed_loop_algorithm_samples/algo_bw.js"]);
#loaded_algo_input['index'] = loaded_algo_input['index']+1
#print(algo_input_list)
#with open("../glucosym/closed_loop_algorithm_samples/algo_input.json", "w") as write_algo_input:
# json.dump(algo_input_list, write_algo_input, indent=4)
#os.chdir("../../myopenaps")
# data_to_prepend = data[0].copy()
#current_time = data_to_prepend["display_time"]
#mytime = datetime.strptime(current_time,"%Y-%m-%dT%H:%M:%S-07:00")
#dt = timedelta(minutes = 5)
#mytime += dt
#make_time_str = str(mytime).split(' ')
#new_time_str = make_time_str[0]+"T"+make_time_str[1]+"-07:00"
#data_to_prepend["display_time"] = new_time_str
#data_to_prepend["dateString"] = new_time_str
#current_time = data_to_prepend["system_time"]
#mytime = datetime.strptime(current_time,"%Y-%m-%dT%H:%M:%S-07:00")
#dt = timedelta(minutes = 5)
#mytime += dt
#make_time_str = str(mytime).split(' ')
#new_time_str = make_time_str[0]+"T"+make_time_str[1]+"-07:00"
#data_to_prepend["system_time"] = new_time_str
# read_glucose_from_glucosym = open("../glucosym/closed_loop_algorithm_samples/glucose_output_algo_bw.txt", "r")
# loaded_glucose = read_glucose_from_glucosym.read()
#data_to_prepend["glucose"] = int(data_to_prepend["glucose"])-5
# data_to_prepend["glucose"] = loaded_glucose
# data_to_prepend["date"]+= 300000
# call("date -Ins -s $(date -Ins -d '+5 minute')", shell=True)
# data.insert(0, data_to_prepend)
# with open('monitor/glucose.json', 'w') as outfile:
# json.dump(data, outfile, indent=4)
# outfile.close()
#This part is for ploting glucose and insulin data over the time. This section starts after all the iteration is finished
#if _ == iteration_num:
# with open("enact/all_suggested.json") as read_all_suggested:
# loaded_all_suggested = json.load(read_all_suggested)
#y_list = [{"a":1, "b":1},{"a":4, "b":2},{"a":9, "b":3},{"a":16, "b":4}]
#print(loaded_all_suggested)
#glucose = []
#insulin = []
#time = []
#time_index = 0
#for _ in loaded_all_suggested:
# if 'bg' in _.keys() and 'rate' in _.keys():
# glucose.insert(0,_['bg'])
# insulin.insert(0,_['rate'])
# time.append(time_index)
# time_index+=5
#print(glucose)
#print(time)
#plt.plot(time, glucose)
#plt.plot(time, insulin)
#plt.ylabel("glucose and Insulin")
#plt.xlabel("time")
#plt.show()
#print("glucose",glucose)
#print("insulin",insulin)
#print("time",time)
print("\n ########################################")
print("Fault Occurrence:", fault_occurrence, " times")
print("########################################\n")