-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsimulation.py
2215 lines (2173 loc) · 97.4 KB
/
simulation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Created on Sun May 4 22:38:40 2014
@author: Yuxiang Wang
"""
# %%
import pickle
import copy
from itertools import combinations
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.integrate import quad, dblquad
from scipy.stats import pearsonr
from shapely.geometry import Polygon, MultiPolygon, LineString
from shapely.ops import cascaded_union, polygonize, unary_union
from constants import (
DT, FS, FIBER_TOT_NUM, MARKER_LIST, COLOR_LIST, MS, FIBER_MECH_ID,
FIBER_FIT_ID_LIST, LS_LIST, EVAL_DISPL, EVAL_FORCE, FIBER_RCV,
STATIC_START, STATIC_END)
from fitlif import LifModel
BASE_CSV_PATH = 'X:/YuxiangWang/AbaqusFolder/YoshiModel/csvs/'
factor_list = ['SkinThick', 'SkinAlpha', 'SkinGinf', 'SylgardThick',
'SylgardC10']
factor_display_list = ['skin thickness', 'skin modulus',
'skin viscoelasticity', 'substrate thickness',
'substrate modulus']
level_num = 5
control_list = ['Displ', 'Force']
surface_list = ['displ', 'press']
quantity_list = ['displ', 'force', 'press', 'stress', 'strain', 'sener']
quantile_label_list = ['Min', 'Lower-quartile', 'Median',
'Upper-quartile', 'Max']
phase_list = ['dynamic', 'static']
percentage_label_list = ['%d%%' % i for i in range(50, 175, 25)]
displcoeff = np.loadtxt('./csvs/displcoeff.csv', delimiter=',')
stim_num = 6
AREA = np.pi * 1e-3**2 / 4
MAX_RADIUS = .6e-3
MAX_TIME = 5.
MAX_RATE_TIME = .25
stim_plot_list = [1, 2, 3] # Stims to be plotted
level_plot_list = range(level_num)[1:-1]
dist_key_list = ['cpress', 'cxnew', 'cxold', 'cy', 'msener',
'mstrain', 'mstress', 'mxnew', 'mxold', 'my',
'time']
stim_in_geom_plot = 4
def fill_between_curves(x_array_list, y_array_list, axes, **kwargs):
polygons = []
for (i1, x1), (i2, x2) in combinations(enumerate(x_array_list), 2):
y1 = y_array_list[i1]
y2 = y_array_list[i2]
x = np.r_[x1, x2[::-1]]
y = np.r_[y1, y2[::-1]]
polygons.append(Polygon(np.c_[x, y]).buffer(0))
polygons = cascaded_union(polygons)
fill_polygons(polygons, axes, **kwargs)
def fill_between_geom_curves(x_array_list, y_array_list, axes=None, **kwargs):
if axes is None:
fig, axes = plt.subplots()
x_array_list_list, y_array_list_list = [[], []], [[], []]
for i, x in enumerate(x_array_list):
y = y_array_list[i]
maxidx = y.argmax()
endidx = (x > MAX_RADIUS * 1e3).nonzero()[0][0]
x_array_list_list[0].append(x[:maxidx + 1])
x_array_list_list[1].append(x[maxidx:endidx])
y_array_list_list[0].append(y[:maxidx + 1])
y_array_list_list[1].append(y[maxidx:endidx])
polygons_list = []
for list_index, x_array_list in enumerate(x_array_list_list):
y_array_list = y_array_list_list[list_index]
polygons = []
for (i1, x1), (i2, x2) in combinations(enumerate(x_array_list), 2):
y1 = y_array_list[i1]
y2 = y_array_list[i2]
x = np.r_[x1, x2[::-1], x1[0]]
y = np.r_[y1, y2[::-1], y1[0]]
coords = np.c_[x, y]
lr = LineString(coords)
mls = unary_union(lr)
mp = MultiPolygon(list(polygonize(mls)))
polygons.extend(mp)
polygons = cascaded_union(MultiPolygon(polygons).buffer(0))
polygons_list.append(polygons)
final_polygons = cascaded_union(polygons_list)
fill_polygons(final_polygons, axes, **kwargs)
def fill_polygons(polygons, axes, **kwargs):
if isinstance(polygons, MultiPolygon):
for polygon in polygons:
axes.fill(*polygon.exterior.xy, **kwargs)
elif isinstance(polygons, Polygon):
axes.fill(*polygons.exterior.xy, **kwargs)
def get_static_mean(array, max_index):
static_start_index = max_index + int(FS * STATIC_START)
static_end_index = max_index + int(FS * STATIC_END)
static_mean = array[static_start_index:static_end_index].mean()
return static_mean
class SimFiber:
def __init__(self, factor, level, control, stim_num):
"""
Class for simulated model from Abaqus.
Parameters
----------
factor : str
Which part of the mechanics was changed. Options are 'SkinThick',
'SkinAlpha', 'SylgardThick', 'SylgardC10'
level : int
An int in [0, 5]. Corresponds to min., lower-quartile, median,
upper-quartile and max.
control : str
The applied control in simulation, either force or displacement,
noted by 'Force' or 'Displ'.
"""
self.factor = factor
self.level = level
self.control = control
self.stim_num = stim_num
self.get_dist()
self.load_traces()
self.load_trans_params()
self.get_predicted_fr()
self.get_dist_fr()
self.get_mi()
self.get_line_fit()
return
def get_dist(self, key_list=dist_key_list):
fpath = BASE_CSV_PATH
self.dist = [{} for i in range(self.stim_num)]
for stim in range(self.stim_num)[1:]:
for key in key_list:
self.dist[stim][key] = np.loadtxt(
fpath + self.factor + str(self.level) + str(stim - 1) +
self.control + '_'+key+'.csv', delimiter=',')
# Change unit to experiment ones
if 'y' in key:
self.dist[stim][key] = displcoeff[0] + displcoeff[1] *\
self.dist[stim][key]*(-1e6)
argsort = self.dist[stim]['cxold'][-1].argsort()
# Sort order in x
for key in key_list:
# Calculate integration over area
if key.startswith('c'):
self.dist[stim][key] = (self.dist[stim][key].T[argsort]).T
# Propagate time
self.dist[stim]['time'] = np.tile(
self.dist[stim]['time'][:, np.newaxis],
self.dist[stim]['cxold'].shape[1])
# Calculate integration over area
for key in key_list:
if 'time' not in key:
def get_field(r):
return np.interp(r, self.dist[stim][key[0]+'xold'][
-1], self.dist[stim][key][-1])
self.dist[stim][key+'int'] = dblquad(
lambda r, theta: get_field(r) * r,
0, 2 * np.pi,
lambda r: 0,
lambda r: MAX_RADIUS
)[0]
for key, value in self.dist[1].items():
if type(value) is float:
self.dist[0][key] = 0.
if type(value) is np.ndarray and not key == 'time':
self.dist[0][key] = np.zeros_like(value)
elif key == 'time':
self.dist[0][key] = value
def load_trans_params(self):
self.trans_params = []
for fiber_id in range(FIBER_TOT_NUM):
with open('./pickles/trans_params_%d.pkl' % fiber_id, 'rb') as f:
self.trans_params.append(pickle.load(f))
return
def load_traces(self):
fpath = BASE_CSV_PATH
# Use stim_num - 1 to leave space for the zero-stim trace
fname_list = [self.factor + str(self.level) + str(stim) +
self.control + '.csv' for stim in range(self.stim_num-1)]
self.traces = [{} for i in range(self.stim_num)]
self.traces_rate = [{} for i in range(self.stim_num)]
# Read the non-zero output from FEM
for i, fname in enumerate(fname_list):
# Get all quantities
time, force, displ, stress, strain, sener = np.loadtxt(
fpath+fname, delimiter=',').T
press = self.dist[i+1]['cpress'][:, 0]
# Save absolute quantities
fine_time = np.arange(0, time.max(), DT)
self.traces[i+1]['time'] = fine_time
for quantity in quantity_list:
self.traces[i+1][quantity] = np.interp(fine_time, time,
locals()[quantity])
self.traces[i+1]['max_index'] = self.traces[i+1]['force'].argmax()
# Save rate quantities
fine_time = np.arange(0, time[-1], DT)
self.traces_rate[i+1]['time'] = fine_time
for quantity in quantity_list:
self.traces_rate[i+1][quantity] = np.interp(
fine_time, time[:-1],
np.diff(locals()[quantity])/np.diff(time))
self.traces_rate[i+1]['max_index'] = self.traces[i+1]['max_index']
# Fill the zero-stim trace
self.traces[0]['max_index'] = self.traces[1]['max_index']
self.traces[0]['time'] = self.traces[1]['time']
self.traces_rate[0]['max_index'] = self.traces_rate[1]['max_index']
self.traces_rate[0]['time'] = self.traces_rate[1]['time']
for quantity in quantity_list:
self.traces[0][quantity] = np.zeros_like(self.traces[0]['time'])
self.traces_rate[0][quantity] = np.zeros_like(
self.traces_rate[0]['time'])
# Scale the displ
for i in range(self.stim_num):
self.traces[i]['displ'] = displcoeff[0] * 1e-6 +\
displcoeff[1] * self.traces[i]['displ']
# Get the FEM and corresponding displ / force
self.static_displ_exp = np.array(
[get_static_mean(self.traces[i]['displ'],
self.traces[i]['max_index'])
for i in range(self.stim_num)]) * 1e3
self.dynamic_displ_exp = np.array(
[self.traces[i]['displ'][self.traces[i]['max_index']]
for i in range(self.stim_num)]) * 1e3
self.static_force_fem = np.array(
[get_static_mean(self.traces[i]['force'],
self.traces[i]['max_index'])
for i in range(self.stim_num)])
self.dynamic_force_fem = np.array(
[self.traces[i]['force'].max() for i in range(self.stim_num)])
self.static_force_exp = self.static_force_fem * 1e3
self.dynamic_force_exp = self.dynamic_force_fem * 1e3
# Get the avg displ / force rate
self.displ_rate_exp = np.array(
[self.dynamic_displ_exp[i] / self.traces[i]['max_index'] / DT
for i in range(self.stim_num)])
self.force_rate_exp = np.array(
[self.dynamic_force_exp[i] / self.traces[i]['max_index'] / DT
for i in range(self.stim_num)])
return
def get_predicted_fr(self, trans_params=None):
"""
Returns the predicted fr based on the instance's stress/strain/sener.
1) If `trans_params is None`:
Perform calculation on the instance's current `self.trans_params`
and save data to `self.predicted_fr`;
2) Otherwise:
Sepcify `trans_params` and return the `predicted_fr` w/o
updating the instance's properties.
Note: do `copy.deepcopy()` before modifying the old `trans_params`!
"""
# Determine whether a static call or not
update_instance = False
if trans_params is None:
update_instance = True
trans_params = self.trans_params
# Calculate predicted fr
predicted_fr = [{} for i in range(FIBER_TOT_NUM)]
for fiber_id in FIBER_FIT_ID_LIST:
for quantity in quantity_list[-3:]:
# Get the quantity_dict_list for input
quantity_dict_list = [{
'quantity_array': self.traces[i][quantity],
'max_index': self.traces[i]['max_index']}
for i in range(self.stim_num)]
# Calculate
lifModel = LifModel(**FIBER_RCV[fiber_id])
predicted_fr[fiber_id][quantity] =\
lifModel.trans_param_to_predicted_fr(
quantity_dict_list, trans_params[fiber_id][quantity])
# Update instance if needed
if update_instance:
self.predicted_fr = predicted_fr
return predicted_fr
def get_dist_fr(self, trans_params=None):
# Determine whether a static call or not
update_instance = False
if trans_params is None:
update_instance = True
trans_params = self.trans_params
# Calculate predicted fr
total_elem_num = self.dist[-1]['mstress'].shape[1]
dist_fr = [{} for i in range(FIBER_TOT_NUM)]
for fiber_id in FIBER_FIT_ID_LIST:
for quantity in quantity_list[-3:]:
dist_fr[fiber_id][quantity] = np.empty((
self.stim_num, 2, total_elem_num))
for elem in range(total_elem_num):
# Get the quantity_dict_list for input
quantity_dict_list = [{
'quantity_array':
np.interp(np.arange(0, self.dist[i]['time'].max(),
DT),
self.dist[i]['time'][:, 0],
self.dist[i]['m' + quantity][:, elem]),
'max_index': self.traces[i]['max_index']}
for i in range(self.stim_num)]
# Calculate
lifModel = LifModel(**FIBER_RCV[fiber_id])
dist_fr[fiber_id][quantity][:, :, elem] =\
lifModel.trans_param_to_predicted_fr(
quantity_dict_list,
trans_params[fiber_id][quantity])[:, 1:]
# Update instance if needed
if update_instance:
self.dist_fr = dist_fr
return dist_fr
def get_mi(self):
def calculate_m(fr_array):
rmax = fr_array.max()
rmin = fr_array.min()
if rmax != rmin:
rmin = fr_array[0]
m = (rmax - rmin) / (rmax + rmin)
else:
m = 0
return m
mi = [{} for i in range(FIBER_TOT_NUM)]
for fiber_id in FIBER_FIT_ID_LIST:
for quantity in quantity_list[-3:]:
mi[fiber_id][quantity] = np.empty((self.stim_num, 2))
for stim in range(self.stim_num):
for phase in range(2):
mi[fiber_id][quantity][stim, phase] = calculate_m(
self.dist_fr[fiber_id][quantity][stim, phase, :])
self.mi = mi
return mi
def get_predicted_spike_array(self, trans_params=None):
# Determine whether a static call or not
update_instance = False
if trans_params is None:
update_instance = True
trans_params = self.trans_params
# Calculate predicted spike array
predicted_spike_array = [{} for i in range(FIBER_TOT_NUM)]
for fiber_id in FIBER_FIT_ID_LIST:
for quantity in quantity_list[-3:]:
# Get the quantity_dict_list for input
quantity_dict_list = [{
'quantity_array': self.traces[i][quantity],
'max_index': self.traces[i]['max_index']}
for i in range(self.stim_num)]
# Calculate
lifModel = LifModel(**FIBER_RCV[fiber_id])
predicted_spike_array[fiber_id][quantity] =\
lifModel.trans_param_to_predicted_spike_array(
quantity_dict_list, trans_params[fiber_id][quantity])
# Update instance if needed
if update_instance:
self.predicted_spike_array = predicted_spike_array
return predicted_spike_array
def get_line_fit(self):
self.line_fit = [{} for i in range(FIBER_TOT_NUM)]
self.line_fit_median_predict = [{} for i in range(FIBER_TOT_NUM)]
for fiber_id in FIBER_FIT_ID_LIST:
for quantity in quantity_list[-3:]:
self.line_fit[fiber_id][quantity] = {
'displ_dynamic': np.polyfit(
self.dynamic_displ_exp,
self.predicted_fr[fiber_id][quantity][:, 2], 1),
'displ_static': np.polyfit(
self.static_displ_exp,
self.predicted_fr[fiber_id][quantity][:, 1], 1),
'force_dynamic': np.polyfit(
self.dynamic_force_exp,
self.predicted_fr[fiber_id][quantity][:, 2], 1),
'force_static': np.polyfit(
self.static_force_exp,
self.predicted_fr[fiber_id][quantity][:, 1], 1)}
self.line_fit_median_predict[fiber_id][quantity] = {
key: np.polyval(
self.line_fit[fiber_id][quantity][key],
globals()['EVAL_' + key[:5].upper()])
for key in iter(self.line_fit[fiber_id][quantity])}
def plot_predicted_fr(self, axs, fiber_id, **kwargs):
if self.control is 'Displ':
for i, quantity in enumerate(quantity_list[-3:]):
axs[i, 1].plot(
self.static_displ_exp,
self.predicted_fr[fiber_id][quantity][:, 1],
**kwargs)
axs[i, 0].plot(
self.static_displ_exp,
self.predicted_fr[fiber_id][quantity][:, 2],
**kwargs)
if self.control is 'Force':
for i, quantity in enumerate(quantity_list[-3:]):
axs[i, 1].plot(
self.static_force_exp,
self.predicted_fr[fiber_id][quantity][:, 1],
**kwargs)
axs[i, 0].plot(
self.static_force_exp,
self.predicted_fr[fiber_id][quantity][:, 2],
**kwargs)
if __name__ == '__main__':
run_fiber = False
# Load experiment data
binned_exp_list = []
for i in range(FIBER_TOT_NUM):
with open('./pickles/binned_exp_%d.pkl' % i, 'rb') as f:
binned_exp_list.append(pickle.load(f))
fname = './pickles/simFiberList.pkl'
if run_fiber:
# Generate data
simFiberList = [[[] for j in
range(level_num)] for i in range(len(factor_list))]
for i, factor in enumerate(factor_list):
for level in range(level_num):
j = level
for k, control in enumerate(control_list):
simFiber = SimFiber(factor, level, control, stim_num)
simFiberList[i][j].append(simFiber)
print(factor+str(level)+control+' is done.')
# Store data
with open(fname, 'wb') as f:
pickle.dump(simFiberList, f)
else:
with open(fname, 'rb') as f:
simFiberList = pickle.load(f)
# %% Generate table for integration
spatial_table = np.empty([6, 3])
for i, factor in enumerate(factor_list[:3]):
for j, control in enumerate(control_list):
for k, quantity in enumerate(quantity_list[-3:]):
iqr = np.abs(simFiberList[i][3][j].dist[
2]['m%sint' % quantity] - simFiberList[i][1][j].dist[
2]['m%sint' % quantity])
distance = .5 * np.abs(simFiberList[i][2][j].dist[
3]['m%sint' % quantity] - simFiberList[i][2][j].dist[
1]['m%sint' % quantity])
spatial_table[3*j+k, i] = iqr / distance
spatial_table_sum = spatial_table.sum(axis=1)
np.savetxt('./csvs/spatial_table.csv', spatial_table, delimiter=',')
# %% Calculate Pearson correlation coefficients
"""
Three rows stand for three quantities, two columns for two controls.
Ignore the effects for each factors since it wouldn't matter.
"""
spatial_pearsonr_table = np.empty([3, 2])
spatial_pearsonp_table = np.empty_like(spatial_pearsonr_table)
for i, quantity in enumerate(quantity_list[-3:]):
for j, control in enumerate(control_list):
dist = simFiberList[0][2][j].dist[3]
xcoord = np.linspace(0, MAX_RADIUS, 100)
# Get surface data
if control == 'Force':
surface_quantity = 'cpress'
elif control == 'Displ':
surface_quantity = 'cy'
surface_data = np.interp(xcoord, dist['cxold'][-1],
dist[surface_quantity][-1])
# Get mcnc data
mcnc_data = np.interp(xcoord, dist['mxold'][-1],
dist['m'+quantity][-1])
# Calculate correlation
spatial_pearsonr_table[i, j], spatial_pearsonp_table[i, j] = \
pearsonr(surface_data, mcnc_data)
np.savetxt('./csvs/spatial_r2_table.csv', spatial_pearsonr_table**2,
delimiter=',')
# %% Plot distribution
fig, axs = plt.subplots(5, 2, figsize=(6.83, 9.19), sharex=True)
mquantity_list = ['mstress', 'mstrain', 'msener']
cquantity_list = ['cy', 'cpress']
for i, factor in enumerate(factor_list[:3]):
for j, control in enumerate(control_list):
for level in level_plot_list:
for stim in stim_plot_list:
alpha = 1. - .65 * abs(level - 2)
if stim == 2:
color = (0, 0, 0, alpha)
elif stim == 1:
color = (1, 0, 0, alpha)
elif stim == 3:
color = (0, 0, 1, alpha)
ls = LS_LIST[i]
dist = simFiberList[i][level][j].dist[stim]
xscale = 1e3
for row, cquantity in enumerate(cquantity_list):
# Scaling the axes
if 'y' in cquantity:
cscale = 1e-3
elif 'ress' in cquantity:
cscale = 1e-3
# Plotting
axs[row, j].plot(
dist['cxold'][-1, :] * xscale,
dist[cquantity][-1, :] * cscale,
ls=ls, color=color,
label=quantile_label_list[level])
for row, mquantity in enumerate(mquantity_list):
# Scaling the axes
if 'ress' in mquantity or 'sener' in mquantity:
mscale = 1e-3
else:
mscale = 1
# Plotting
axs[row+2, j].plot(
dist['mxold'][-1, :] * xscale,
dist[mquantity][-1, :] * mscale,
ls=ls, color=color,
label=quantile_label_list[level])
# Set x and y lim
for axes in axs.ravel():
axes.set_xlim(0, MAX_RADIUS*1e3)
# Formatting labels
for axes in axs[-1, :]:
axes.set_xlabel('Location (mm)')
axs[0, 0].set_ylabel(r'Surface deflection (mm)')
axs[1, 0].set_ylabel(r'Surface pressure (kPa)')
axs[2, 0].set_ylabel('Internal stress (kPa)')
axs[3, 0].set_ylabel('Internal strain')
axs[4, 0].set_ylabel(r'Internal SED (kPa/$m^3$)')
# Added panel labels
for axes_id, axes in enumerate(axs.ravel()):
if axes_id // 2 in [0]:
xloc = -.135
elif axes_id // 2 in [1, 2]:
xloc = -0.105
elif axes_id // 2 in [3, 4]:
xloc = -.12
axes.text(xloc, 1.1, chr(65+axes_id), transform=axes.transAxes,
fontsize=12, fontweight='bold', va='top')
# Add legends
# The line type labels
handles, labels = axs[0, 0].get_legend_handles_labels()
axs[0, 0].legend(
handles[len(stim_plot_list)*(len(level_plot_list)//2) +
len(stim_plot_list)//2::len(stim_plot_list)*len(
level_plot_list)],
[factor_display[5:].capitalize()
for factor_display in factor_display_list[:3]], loc=3)
# The 5 quantile labels
axs[0, 1].legend(handles[1:3*len(level_plot_list)+1:3], [
'Quartile', 'Median'], loc=3)
# Add subtitles
axs[0, 0].set_title('Deflection controlled')
axs[0, 1].set_title('Pressure controlled')
# Save figure
fig.tight_layout()
fig.savefig('./plots/spatial_distribution.png', dpi=300)
plt.close(fig)
# %% Calculating iqr for all temporal traces
# Calculate iqrs
def calculate_iqr(simFiberLevelList, end_time=MAX_TIME):
def integrate(simFiber, quantity, stim):
time = simFiber.traces[stim]['time']
trace = simFiber.traces[stim][quantity]
integration = quad(
lambda t: np.interp(t, time, trace),
time[0], end_time)[0]
return integration
iqr_dict, distance_dict = {}, {}
for quantity in quantity_list[-3:]:
iqr_dict[quantity] = \
np.abs(integrate(simFiberLevelList[3], quantity, 2) -
integrate(simFiberLevelList[1], quantity, 2))
distance_dict[quantity] = \
.5 * np.abs(integrate(simFiberLevelList[2], quantity, 1) -
integrate(simFiberLevelList[2], quantity, 3))
return iqr_dict, distance_dict
temporal_table = np.empty((6, 3))
for i, factor in enumerate(factor_list[:3]):
for k, control in enumerate(control_list):
iqr_dict, distance_dict = calculate_iqr(
[simFiberList[i][j][k] for j in range(level_num)])
for row, quantity in enumerate(quantity_list[-3:]):
temporal_table[3*k+row, i] = \
iqr_dict[quantity] / distance_dict[quantity]
temporal_table_sum = temporal_table.sum(axis=1)
np.savetxt('./csvs/temporal_table.csv', temporal_table, delimiter=',')
# %% Calculate Pearson correlation coefficients
temporal_pearsonr_table = np.empty([3, 2])
temporal_pearsonp_table = np.empty_like(temporal_pearsonr_table)
for i, quantity in enumerate(quantity_list[-3:]):
for j, control in enumerate(control_list):
trace = simFiberList[0][2][j].traces[3]
end_index = (trace['time'] > MAX_TIME).nonzero()[0][0]
surface = 'press' if control == 'Force' else 'displ'
xdata = trace[surface][:end_index]
ydata = trace[quantity][:end_index]
temporal_pearsonr_table[i, j], temporal_pearsonp_table[i, j] = \
pearsonr(xdata, ydata)
np.savetxt('./csvs/temporal_r2_table.csv', temporal_pearsonr_table**2,
delimiter=',')
# %% Plot temporal traces
fiber_id = FIBER_MECH_ID
fig, axs = plt.subplots(5, 2, figsize=(6.83, 9.19), sharex=True)
for i, factor in enumerate(factor_list[:3]):
for k, control in enumerate(control_list):
control = control.lower()
for level in level_plot_list:
for stim in stim_plot_list:
alpha = 1. - .65 * abs(level - 2)
if stim == 2:
color = (0, 0, 0, alpha)
elif stim == 1:
color = (1, 0, 0, alpha)
elif stim == 3:
color = (0, 0, 1, alpha)
ls = LS_LIST[i]
simFiber = simFiberList[i][level][k]
for row, surface in enumerate(surface_list):
sscale = 1e3 if surface == 'displ' else 1e-3
axs[row, k].plot(
simFiber.traces[stim]['time'],
simFiber.traces[stim][surface] * sscale,
ls=ls, color=color,
label=quantile_label_list[level])
for row, quantity in enumerate(quantity_list[-3:]):
scale = 1 if quantity is 'strain' else 1e-3
axes = axs[row+2, k]
axes.plot(
simFiber.traces[stim]['time'],
simFiber.traces[stim][quantity]*scale,
ls=ls, color=color,
label=quantile_label_list[level])
# Add axes labels
for axes in axs[-1, :]:
axes.set_xlabel('Time (s)')
axs[0, 0].set_ylabel(r'Surface deflection (mm)')
axs[1, 0].set_ylabel(r'Surface pressure (kPa)')
axs[2, 0].set_ylabel('Internal stress (kPa)')
axs[3, 0].set_ylabel('Internal strain')
axs[4, 0].set_ylabel(r'Internal SED (kPa/$m^3$)')
# Formatting
for axes_id, axes in enumerate(axs.ravel()):
if axes_id // 2 in [0, 3, 4]:
xloc = -.135
else:
xloc = -0.12
axes.text(xloc, 1.1, chr(65+axes_id), transform=axes.transAxes,
fontsize=12, fontweight='bold', va='top')
axes.set_xlim(-.0, MAX_TIME)
# Add legends
# The line type labels
handles, labels = axs[0, 0].get_legend_handles_labels()
axs[0, 0].legend(
handles[len(stim_plot_list)*(len(level_plot_list)//2) +
len(stim_plot_list)//2::len(stim_plot_list)*len(
level_plot_list)],
[factor_display[5:].capitalize()
for factor_display in factor_display_list[:3]], loc=4)
# The 5 quantile labels
axs[0, 1].legend(handles[1:3*len(level_plot_list)+1:3], [
'Quartile', 'Median'], loc=4)
# Add subtitles
axs[0, 0].set_title('Deflection controlled')
axs[0, 1].set_title('Pressure controlled')
# Save figure
fig.tight_layout()
fig.savefig('./plots/temporal_distribution.png', dpi=300)
plt.close(fig)
# %% Calculating iqr for all Stimulus rate over time traces
# Calculate iqrs
def calculate_rate_iqr(simFiberLevelList, end_time=MAX_RATE_TIME):
def integrate_rate(simFiber, quantity, stim):
time = simFiber.traces[stim]['time'][:-1]
dt = time[1] - time[0]
trace = np.diff(simFiber.traces[stim][quantity])/dt
integration = quad(
lambda t: np.interp(t, time, trace),
time[0], time[-1])[0]
return integration
iqr_dict, distance_dict = {}, {}
for quantity in quantity_list[-3:]:
iqr_dict[quantity] = \
np.abs(integrate_rate(simFiberLevelList[3], quantity, 2) -
integrate_rate(simFiberLevelList[1], quantity, 2))
distance_dict[quantity] = \
.5 * np.abs(integrate_rate(simFiberLevelList[2], quantity, 1) -
integrate_rate(simFiberLevelList[2], quantity, 3))
return iqr_dict, distance_dict
temporal_rate_table = np.empty((6, 3))
for i, factor in enumerate(factor_list[:3]):
for k, control in enumerate(control_list):
iqr_dict, distance_dict = calculate_rate_iqr(
[simFiberList[i][j][k] for j in range(level_num)])
for row, quantity in enumerate(quantity_list[-3:]):
temporal_rate_table[3*k+row, i] = \
iqr_dict[quantity] / distance_dict[quantity]
temporal_rate_table_sum = temporal_table.sum(axis=1)
np.savetxt('./csvs/temporal_rate_table.csv', temporal_rate_table,
delimiter=',')
# %% Plot temporal trace rate
# Calculate Pearson correlation coefficients
temporal_rate_pearsonr_table = np.empty([3, 2])
temporal_rate_pearsonp_table = np.empty_like(temporal_rate_pearsonr_table)
for i, quantity in enumerate(quantity_list[-3:]):
for j, control in enumerate(control_list):
trace = simFiberList[0][2][j].traces[3]
end_index = (trace['time'] > MAX_RATE_TIME).nonzero()[0][0]
surface = 'press' if control == 'Force' else 'displ'
xdata = np.diff(trace[surface][:end_index])
ydata = np.diff(trace[quantity][:end_index])
temporal_rate_pearsonr_table[i, j], \
temporal_rate_pearsonp_table[i, j] = pearsonr(xdata, ydata)
np.savetxt('./csvs/temporal_rate_r2_table.csv',
temporal_rate_pearsonr_table**2, delimiter=',')
# %% Plot Stimulus rate over time traces
fiber_id = FIBER_MECH_ID
fig, axs = plt.subplots(5, 2, figsize=(6.83, 9.19), sharex=True)
for i, factor in enumerate(factor_list[:3]):
for k, control in enumerate(control_list):
control = control.lower()
for level in level_plot_list:
for stim in stim_plot_list:
alpha = 1. - .65 * abs(level - 2)
if stim == 2:
color = (0, 0, 0, alpha)
elif stim == 1:
color = (1, 0, 0, alpha)
elif stim == 3:
color = (0, 0, 1, alpha)
ls = LS_LIST[i]
simFiber = simFiberList[i][level][k]
for row, surface in enumerate(surface_list):
sscale = 1e3 if surface == 'displ' else 1e-3
axs[row, k].plot(
simFiber.traces_rate[stim]['time'],
simFiber.traces_rate[stim][surface] * sscale,
ls=ls, color=color,
label=quantile_label_list[level])
for row, quantity in enumerate(quantity_list[-3:]):
scale = 1 if quantity is 'strain' else 1e-3
axes = axs[row+2, k]
axes.plot(
simFiber.traces_rate[stim]['time'],
simFiber.traces_rate[stim][quantity] * scale,
ls=ls, color=color,
label=quantile_label_list[level])
# Add axes labels
for axes in axs[-1, :]:
axes.set_xlabel('Time (s)')
axs[0, 0].set_ylabel(r'Surface velocity (mm/s)')
axs[1, 0].set_ylabel(r'Surface pressure rate (kPa/s)')
axs[2, 0].set_ylabel(r'Internal stress rate (kPa/s)')
axs[3, 0].set_ylabel(r'Internal strain rate (s$^{-1}$)')
axs[4, 0].set_ylabel(r'Internal SED rate (kPa$\cdot m^3$/s)')
# Added panel labels
for axes_id, axes in enumerate(axs.ravel()):
if axes_id // 2 in [0]:
xloc = -.135
elif axes_id // 2 in [1, 2]:
xloc = -0.105
elif axes_id // 2 in [3, 4]:
xloc = -.12
axes.text(xloc, 1.1, chr(65+axes_id), transform=axes.transAxes,
fontsize=12, fontweight='bold', va='top')
axes.set_xlim(-.0, MAX_RATE_TIME)
# Add legends
# The line type labels
handles, labels = axs[0, 0].get_legend_handles_labels()
axs[0, 0].legend(
handles[len(stim_plot_list) * (len(level_plot_list) // 2) +
len(stim_plot_list) // 2::len(stim_plot_list) * len(
level_plot_list)],
[factor_display[5:].capitalize()
for factor_display in factor_display_list[:3]],
loc=1)
# The 5 quantile labels
axs[0, 1].legend(handles[1:3*len(level_plot_list)+1:3], [
'Quartile', 'Median'], loc=1)
# Add subtitles
axs[0, 0].set_title('Deflection controlled')
axs[0, 1].set_title('Pressure controlled')
# Save figure
fig.tight_layout()
fig.savefig('./plots/temporal_rate_distribution.png', dpi=300)
plt.close(fig)
# %% The function to calculate the supra-threshold sensitivity
def get_sensitivity_function(x, y, supra_threshold=False):
if y.any():
start_index = 0
if supra_threshold:
start_index = y.nonzero()[0][0]
slope = np.polyfit(
x[start_index:], y[start_index:], 1)[0]
else:
slope = 0
return slope
# %% Calculate all the IQRs and compare force vs. displ
fiber_id = FIBER_MECH_ID
def get_slope_iqr(simFiberLevelList, quantity):
"""
Returns
-------
slope_iqr : list
The 1st element for displ., 2nd for force.
"""
slope_list_displ = [get_sensitivity_function(
simFiber.static_displ_exp,
simFiber.predicted_fr[fiber_id][quantity].T[1],
supra_threshold=False)
for simFiber in simFiberLevelList]
slope_list_force = [get_sensitivity_function(
simFiber.static_force_exp,
simFiber.predicted_fr[fiber_id][quantity].T[1],
supra_threshold=False)
for simFiber in simFiberLevelList]
slope_iqr = []
slope_iqr.append(np.abs(
(slope_list_displ[3] - slope_list_displ[1]) / slope_list_displ[2]))
slope_iqr.append(np.abs(
(slope_list_force[3] - slope_list_force[1]) / slope_list_force[2]))
return slope_iqr
sim_table = np.empty((6, 3))
for i, factor in enumerate(factor_list[:3]):
for k, quantity in enumerate(quantity_list[-3:]):
simFiberLevelList = [simFiberList[i][level][0] for level in
range(level_num)]
slope_iqr = get_slope_iqr(simFiberLevelList, quantity)
sim_table[k, i] = slope_iqr[0]
sim_table[3+k, i] = slope_iqr[1]
sim_table_sum = sim_table.sum(axis=1)
np.savetxt('./csvs/sim_table.csv', sim_table, delimiter=',')
# %% Calculate all the IQRs and compare force vs. displ rate
fiber_id = FIBER_MECH_ID
def get_slope_iqr_rate(simFiberLevelList, quantity):
"""
Returns
-------
slope_iqr : list
The 1st element for displ., 2nd for force.
"""
slope_list_displ = [get_sensitivity_function(
simFiber.displ_rate_exp,
simFiber.predicted_fr[fiber_id][quantity][:, 2],
supra_threshold=False)
for simFiber in simFiberLevelList]
slope_list_force = [get_sensitivity_function(
simFiber.force_rate_exp,
simFiber.predicted_fr[fiber_id][quantity][:, 2],
supra_threshold=False)
for simFiber in simFiberLevelList]
slope_iqr = []
slope_iqr.append(np.abs(
(slope_list_displ[3] - slope_list_displ[1]) / slope_list_displ[2]))
slope_iqr.append(np.abs(
(slope_list_force[3] - slope_list_force[1]) / slope_list_force[2]))
return slope_iqr
sim_table_rate = np.empty((6, 3))
for i, factor in enumerate(factor_list[:3]):
for k, quantity in enumerate(quantity_list[-3:]):
simFiberLevelList = [simFiberList[i][level][0] for level in
range(level_num)]
slope_iqr = get_slope_iqr_rate(simFiberLevelList, quantity)
sim_table_rate[k, i] = slope_iqr[0]
sim_table_rate[3+k, i] = slope_iqr[1]
sim_table_rate_sum = sim_table_rate.sum(axis=1)
np.savetxt('./csvs/sim_table_rate.csv', sim_table_rate, delimiter=',')
# %% Calculate all the IQRs and compare force vs. displ geometry
fiber_id = FIBER_MECH_ID
stim = stim_in_geom_plot
def get_dr_iqr_geometry(simFiberLevelListDispl, simFiberLevelListForce,
quantity):
"""
Returns
-------
dr_iqr : list
The 1st element for displ., 2nd for force.
"""
def get_dr(fr_coarse, x_coarse, res=0.1):
x_fine = np.arange(0, 1, res)
fr_fine = np.interp(x_fine, x_coarse, fr_coarse)
max_index = fr_fine.argmax()
dr = fr_fine[max_index] - fr_fine[max_index - 1] +\
fr_fine[max_index] - fr_fine[max_index + 1]
return dr
dr_displ_list = [
get_dr(simFiber.dist_fr[fiber_id][quantity][stim, 0, :],
simFiber.dist[-1]['mxold'][0] * 1e-3)
for simFiber in simFiberLevelListDispl]
dr_force_list = [
get_dr(simFiber.dist_fr[fiber_id][quantity][stim, 0, :],
simFiber.dist[-1]['mxold'][0] * 1e-3)
for simFiber in simFiberLevelListForce]
dr_iqr = []
dr_iqr.append(np.abs(
(dr_displ_list[3] - dr_displ_list[1]) / dr_displ_list[2]))
dr_iqr.append(np.abs(
(dr_force_list[3] - dr_force_list[1]) / dr_force_list[2]))
return dr_iqr
sim_table_geometry = np.empty((6, 3))
for i, factor in enumerate(factor_list[:3]):
for k, quantity in enumerate(quantity_list[-3:]):
simFiberLevelListDispl = [
simFiberList[i][level][0] for level in range(level_num)]
simFiberLevelListForce = [
simFiberList[i][level][1] for level in range(level_num)]
dr_iqr = get_dr_iqr_geometry(
simFiberLevelListDispl, simFiberLevelListForce, quantity)
sim_table_geometry[k, i] = dr_iqr[0]
sim_table_geometry[3+k, i] = dr_iqr[1]
sim_table_geometry_sum = sim_table_geometry.sum(axis=1)
np.savetxt('./csvs/sim_table_geometry.csv', sim_table_geometry,
delimiter=',')
# %% Start plotting
# Factors explaining the force-alignment - static
for fiber_id in FIBER_FIT_ID_LIST:
fig, axs = plt.subplots(3, 3, figsize=(6.83, 6))
for i, factor in enumerate(factor_list[:3]):
for k, quantity in enumerate(quantity_list[-3:]):
# for level in level_plot_list:
for level in range(level_num):
alpha = 1. - .4 * abs(level-2)
color = (0, 0, 0, alpha)
fmt = LS_LIST[i]
label = quantile_label_list[level]
simFiber = simFiberList[i][level][0]
axs[0, k].plot(
simFiber.static_displ_exp,
simFiber.static_force_exp,
color=color, mec=color, ms=MS,
ls=fmt, label=label)
axs[1, k].plot(
simFiber.static_displ_exp,
simFiber.predicted_fr[fiber_id][quantity].T[1],
color=color, mec=color, ms=MS,
ls=fmt, label=label)
axs[2, k].plot(
simFiber.static_force_exp,
simFiber.predicted_fr[fiber_id][quantity].T[1],
color=color, mec=color, ms=MS,
ls=fmt, label=label)
# X and Y limits
for axes in axs[0:, :].ravel():
axes.set_ylim(0, 15)
for axes in axs[1:, :].ravel():
axes.set_ylim(0, 50)
for axes in axs[:2, :].ravel():
axes.set_xlim(.35, .75)
axes.set_xticks(np.arange(.35, .85, .1))
for axes in axs[2, :].ravel():
axes.set_xlim(0, 15)
# Axes and panel labels
for i, axes in enumerate(axs[0, :].ravel()):
axes.set_title('%s-based Model' % ['Stress', 'Strain', 'SED'][i])
for axes in axs[:2, :].ravel():
axes.set_xlabel(r'Static displacement (mm)')
for axes in axs[2, :].ravel():
axes.set_xlabel('Static force (mN)')
for axes in axs[0, :1].ravel():
axes.set_ylabel('Static force (mN)')
for axes in axs[1:, 0].ravel():
axes.set_ylabel('Predicted mean firing (Hz)')
for axes_id, axes in enumerate(axs.ravel()):
axes.text(-.175, 1.1, chr(65+axes_id), transform=axes.transAxes,
fontsize=12, fontweight='bold', va='top')
# Legend
# The line type labels
handles, labels = axs[0, 0].get_legend_handles_labels()
axs[0, 0].legend(handles[2::5], ['Thickness', 'Modulus', 'Visco.'],
loc=2)
# The 5 quantile labels
axs[0, 1].legend(handles[:3], ['Extreme', 'Quartile',
'Median'], loc=2)
# Save
fig.tight_layout()
fig.savefig('./plots/sim_compare_variance_%d.png' % fiber_id, dpi=300)
fig.savefig('./plots/sim_compare_variance_%d.pdf' % fiber_id, dpi=300)