-
Notifications
You must be signed in to change notification settings - Fork 0
/
WALiSuite_V2.0.py
3366 lines (2452 loc) · 168 KB
/
WALiSuite_V2.0.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
# ## Crawl in the directory, load data in
# In[38]:
## The InLight col we have in the count csv files and count tab in the tdms file is based on cX data. Meaning that we're doing
## head tracking but not using in the PI calculation.
## Here, I wrote a function to generate InLight column for a given HeadX coordinates and respective borders.
## I send only the headX while light ON (pattern01 or pattern10) to this function and return a binary list.
def InLightDetection(data,minimumBorder,maximumBorder):
InLightBasedOnHeadXcoords = []
for i in range(len(data)):
if minimumBorder <= data[i] <= maximumBorder:
InLightBasedOnHeadXcoords.append(1)
else:
InLightBasedOnHeadXcoords.append(0)
return InLightBasedOnHeadXcoords
## Since the FPS from different cameras can be different, here I detect the FPS automatically rather than relying on user input.
def detectFPS(timeStamps):
Second_prev = 0
counter = 0
fpsDict= {}
for i in range(len(timeStamps)):
Second_next = timeStamps[i].second
if Second_next == Second_prev:
counter += 1
else:
fpsDict[Second_prev] = counter
counter = 0
Second_prev = Second_next
fps = Counter(fpsDict.values()).most_common()[0][0]
return fps
def dataToDataframe(rootDir):
## Generate a single dataframe from the .tdms and pattern files
temp = {'Tdms file name':[],'Date':[],'Time':[],'mmPerPix':[],'fps':[],'Light Intensity(uW/mm2)':[],'Light Type':[],'Wind status':[],
'Satiety':[],'Genotype':[],'Sex':[],'Status':[],'Fly ID':[],'cX(pix)':[],'HeadX(pix)':[],'HeadX(pix)_smoothed':[],
'HeadY(pix)':[], 'InLight':[],'InLight_HeadX|P01':[],'InLight_HeadX|P10':[],'First light contact index_of_the_whole_data|P01':[],'First light contact index_of_the_whole_data|P10':[],
'LightON index|P01':[],'First light contact index in P01':[],'First light contact index in P10':[],'LightON index|P10':[],'Border|P01':[],'Border|P10':[]}
# Removed 'Light type':[], since all constant
slidingWindowSizeinframes = 25
numOfTdmsFiles = 0
## get access to the files in each ORN folder
fileList = os.listdir(rootDir)
bar = progressbar.ProgressBar()
## Loop thru the file list to find tdms files and their related csv pattern files
for fname in bar(fileList):
if fname[-5:] == '.tdms':
numOfTdmsFiles += 1
## Open the tdms file
f = TdmsFile(os.path.join(rootDir,fname))
## Load the tdms into a pandas df
TDMSdf = f.as_dataframe()
try:
## Open the pattern csv files to extract light border info per fly
tdmsNameNoExtension = fname[:-5]
P01_fname = tdmsNameNoExtension + '_Pattern01.csv'
P10_fname = tdmsNameNoExtension + '_Pattern10.csv'
P01_df = pd.read_csv(os.path.join(rootDir,P01_fname))
P10_df = pd.read_csv(os.path.join(rootDir,P10_fname))
except:
print 'No pattern file(s) for %s' %(tdmsNameNoExtension)
## Get exp info from the tdms filename
tdmsNameNoExtension = tdmsNameNoExtension.split('_')
# print tdmsNameNoExtension
date = tdmsNameNoExtension[1]
time = tdmsNameNoExtension[2]
genotype = tdmsNameNoExtension[3][3:]
sex = "male"
## This is an extra step for hypenated file names
tdmsNameNoExtension_byhypen = tdmsNameNoExtension[4].split('-')
# print tdmsNameNoExtension_byhypen
intensity = tdmsNameNoExtension_byhypen[0][3:]
lightType = tdmsNameNoExtension_byhypen[1]
windState = tdmsNameNoExtension_byhypen[2]
# intensity = tdmsNameNoExtension[4][3:]
# lightType = tdmsNameNoExtension[5]
# windState = tdmsNameNoExtension[6]
satiety = "fileName"
## Get the mm per pixel coefficient
metaData = f.object().properties
mmPerPix = metaData['X_mm_per_pixel']
## Detect the fps of the data for the LXS metric
timeStamps = pd.to_datetime(TDMSdf["/\'Count\'/\'Time'"])
fps = detectFPS(timeStamps)
## Get status info
if ('w1118' in genotype) | ('W1118' in genotype):
status = 'Parent'
elif (('Gal4' in genotype) | ('GAL4' in genotype)) & ('UAS' in genotype):
status = 'Offspring'
else:
status = 'Unknown'
print 'Unknown parental status in file %s' % (fname)
## simply putting fly IDs as numbers does not work due to missing chambers (i.e 3,4,6,7)
## thus, get a list of column names with fly IDs
listOfFlyIDs = TDMSdf.columns[TDMSdf.columns.str.contains("/'Tracker'/'HeadX_pix")]
for fly in listOfFlyIDs:
## get the fly ID from the data itself
flyIndex = int(fly[-4:-1])
## format the fly index into 3 digits number,i.e '5' >> '005'
flyID = format(str(flyIndex).zfill(3))
## generate column names for the data need to be pulled from the df
fly_cX_pix_ID = "/\'Count\'/\'Obj%s_cX'" % flyIndex
fly_inLight_ID = "/\'Count\'/\'Obj%s_InLight'" % flyIndex
fly_headX_pix_ID = "/'Tracker'/'HeadX_pix" + str(flyID) + "'"
fly_headY_pix_ID = "/'Tracker'/'HeadY_pix" + str(flyID) + "'"
temp['Fly ID'].append(flyID)
temp['cX(pix)'].append(TDMSdf[fly_cX_pix_ID].values.astype(float))
temp['InLight'].append(TDMSdf[fly_inLight_ID].values.astype(float))
temp['HeadX(pix)'].append(TDMSdf[fly_headX_pix_ID].values.astype(float))
temp['HeadX(pix)_smoothed'].append(pd.rolling_mean(TDMSdf[fly_headX_pix_ID].values.astype(float),
window = slidingWindowSizeinframes, center=True, win_type="triang"))
temp['HeadY(pix)'].append(TDMSdf[fly_headY_pix_ID].values.astype(float))
## Get the chunks where the light was ON
TDMSdf_pat01 = TDMSdf[TDMSdf["/\'Count\'/\'PatternState'"] == 'Pattern 01']
TDMSdf_pat10 = TDMSdf[TDMSdf["/\'Count\'/\'PatternState'"] == 'Pattern 10']
LightOnP01 = min(TDMSdf_pat01.index),max(TDMSdf_pat01.index)
LightOnP10 = min(TDMSdf_pat10.index),max(TDMSdf_pat10.index)
for fly in listOfFlyIDs:
## get the fly ID from the data itself
flyIndex = int(fly[-4:-1])
## format the fly index into 3 digits number,i.e '5' >> '005'
flyID = format(str(flyIndex).zfill(3))
## generate column names for the data need to be pulled from the df
fly_headX_pix_ID = "/'Tracker'/'HeadX_pix" + str(flyID) + "'"
border_P01 = P01_df.filter(regex='pix').iloc[1].values[flyIndex-1]
border_P10 = P10_df.filter(regex='pix').iloc[1].values[flyIndex-1]
## get the headX coordinates of the fly where the light was ON - pattern01 or pattern10
headXcoord_P01 = TDMSdf_pat01[fly_headX_pix_ID].values.astype(float)
headXcoord_P10 = TDMSdf_pat10[fly_headX_pix_ID].values.astype(float)
## send this data to the function along with the respective border info to get a binary list,
## indicating whether the fly was in the light or not.
## 0 to 146 are min and max limits of the arena. STRICTLY DEPENDING ON YOUR CAMERA!
InLightBasedOnHeadX_P01 = InLightDetection(headXcoord_P01,border_P01,600)
InLightBasedOnHeadX_P10 = InLightDetection(headXcoord_P10,0,border_P10)
## if the fly had ever been in the light, get the first time she did.
if 1 in InLightBasedOnHeadX_P01:
P01_first_light_contact_index_of_the_whole_data = int(LightOnP01[0]) + int(InLightBasedOnHeadX_P01.index(1))
P01_first_light_contact_index_in_the_event = int(InLightBasedOnHeadX_P01.index(1))
else:
P01_first_light_contact_index_of_the_whole_data = None
P01_first_light_contact_index_in_the_event = None
if 1 in InLightBasedOnHeadX_P10:
P10_first_light_contact_index_of_the_whole_data = int(LightOnP10[0]) + int(InLightBasedOnHeadX_P10.index(1))
P10_first_light_contact_index_in_the_event = int(InLightBasedOnHeadX_P10.index(1))
else:
P10_first_light_contact_index_of_the_whole_data = None
P10_first_light_contact_index_in_the_event = None
## append the info to temp dict
temp['First light contact index_of_the_whole_data|P01'].append(P01_first_light_contact_index_of_the_whole_data)
temp['First light contact index_of_the_whole_data|P10'].append(P10_first_light_contact_index_of_the_whole_data)
temp['First light contact index in P01'].append(P01_first_light_contact_index_in_the_event)
temp['First light contact index in P10'].append(P10_first_light_contact_index_in_the_event)
temp['Tdms file name'].append(fname)
temp['Date'].append(date)
temp['Time'].append(time)
temp['mmPerPix'].append(mmPerPix)
temp['fps'].append(fps)
temp['Light Type'].append(lightType)
temp['Light Intensity(uW/mm2)'].append(intensity)
temp['Wind status'].append(windState)
temp['Satiety'].append(satiety)
temp['Genotype'].append(genotype)
temp['Sex'].append(sex)
temp['Status'].append(status)
temp['LightON index|P01'].append(LightOnP01)
temp['LightON index|P10'].append(LightOnP10)
temp['Border|P01'].append(border_P01)
temp['Border|P10'].append(border_P10)
temp['InLight_HeadX|P01'].append(InLightBasedOnHeadX_P01)
temp['InLight_HeadX|P10'].append(InLightBasedOnHeadX_P10)
## Convert temp into a df
colOrder = ['Tdms file name','Date','Time','mmPerPix','fps','Light Intensity(uW/mm2)','Light Type','Wind status',
'Satiety','Genotype','Sex','Status','Fly ID','cX(pix)','HeadX(pix)','HeadX(pix)_smoothed','HeadY(pix)',
'InLight','InLight_HeadX|P01','InLight_HeadX|P10','First light contact index_of_the_whole_data|P01','First light contact index_of_the_whole_data|P10',
'LightON index|P01','First light contact index in P01','First light contact index in P10','LightON index|P10','Border|P01','Border|P10']
results = pd.DataFrame(temp,columns=colOrder)
results.to_pickle(rootDir + '/RawDataFrame.pkl')
## summary of the raw data
summaryTable = results.groupby(['Genotype','Sex','Satiety','Wind status','Light Intensity(uW/mm2)']).size().reset_index(name='counts')
summaryTable.to_csv(rootDir + '/SummaryTableofTheRawData.csv')
return results
# ## Metric: LaXS
# In[2]:
## Usual PI calculation, called by
def calculatePI(data):
numofTimePoints = len(data)
totalTimeinLight = sum(data)
totalTimeinDark = numofTimePoints - totalTimeinLight
PI = float(totalTimeinLight - totalTimeinDark)/float(numofTimePoints)
return PI
def LaXS(df, rootDir,mergeIntensities, combineControls, Xsec = 30, dropNans = False):
numberOfFlies = df.shape[0]
LXS_P01_list = []
LXS_P10_list = []
## calculate LXS PI for each fly/row, and epoch (P01 | P10)
for fly in range(0,numberOfFlies):
## detect how many frames need to take from the tail
numberOfFrames = Xsec * int(df['fps'][fly])
## get the "in light or not" list per epoch
inLight_headX_P01 = df['InLight_HeadX|P01'][fly][-1*numberOfFrames:]
inLight_headX_P10 = df['InLight_HeadX|P10'][fly][-1*numberOfFrames:]
## send them to the calculate PI function
LXS_P01 = calculatePI(inLight_headX_P01)
LXS_P10 = calculatePI(inLight_headX_P10)
## store the PIs in lists
LXS_P01_list.append(LXS_P01)
LXS_P10_list.append(LXS_P10)
## add the new lists of information to the existing df
df = df.assign(LaXS_P01 = pd.Series(LXS_P01_list, index=df.index),
LaXS_P10 = pd.Series(LXS_P10_list, index=df.index))
df = df.assign(LaXS_Mean = pd.Series(df[['LaXS_P01','LaXS_P10']].mean(axis=1),
index=df.index))
plotTheMetric(df,'LaXS',rootDir,mergeIntensities, combineControls)
return None
# ## Metric: TSALE
# In[3]:
def TSALE(df, rootDir,mergeIntensities, combineControls=False, dropNans=False):
numberOfFlies = df.shape[0]
PI_afterLightContact_P01 = []
PI_afterLightContact_P10 = []
## iterate thru the flies to calculate PI scores
## PI scores are calculated seperately for first and second halves of the experiment
for fly in range(0,numberOfFlies):
## get the first light contact index for the fly
firstLightContactIndex_P01 = df['First light contact index in P01'][fly]
firstLightContactIndex_P10 = df['First light contact index in P10'][fly]
## if the light contact index is NOT nan, calculate the PI and attach it to the list
## otherwise attach a np.nan value
if not pd.isnull(firstLightContactIndex_P01):
## select the data after fly was exposed to the light
InLightDatainTheRange_P01 = df['InLight_HeadX|P01'][fly][int(firstLightContactIndex_P01):]
## calculate PI score
numOfDataPoints_P01 = len(InLightDatainTheRange_P01)
numOfInLights_P01 = sum(InLightDatainTheRange_P01)
numOfInDarks_P01 = numOfDataPoints_P01 - numOfInLights_P01
PI_P01 = float(numOfInLights_P01 - numOfInDarks_P01)/float(numOfDataPoints_P01)
PI_afterLightContact_P01.append(PI_P01)
elif pd.isnull(firstLightContactIndex_P01):
PI_afterLightContact_P01.append(np.nan)
else:
None
## same as the first half of the exp: P01
if not pd.isnull(firstLightContactIndex_P10):
InLightDatainTheRange_P10 = df['InLight_HeadX|P10'][fly][int(firstLightContactIndex_P10):]
numOfDataPoints_P10 = len(InLightDatainTheRange_P10)
numOfInLights_P10 = sum(InLightDatainTheRange_P10)
numOfInDarks_P10 = numOfDataPoints_P10 - numOfInLights_P10
PI_P10 = float(numOfInLights_P10 - numOfInDarks_P10)/float(numOfDataPoints_P10)
PI_afterLightContact_P10.append(PI_P10)
elif pd.isnull(firstLightContactIndex_P10):
PI_afterLightContact_P10.append(np.nan)
else:
None
## add the Preference Index pattern01 and pattern10 to the df
df = df.assign(TSALE_P01 = pd.Series(PI_afterLightContact_P01, index=df.index),
TSALE_P10 = pd.Series(PI_afterLightContact_P10, index=df.index))
df = df.assign(TSALE_Mean = pd.Series(df[['TSALE_P01','TSALE_P10']].mean(axis=1), index=df.index))
droppedNans = MeanPreferenceIndexNoNANs(df)
if dropNans == True:
plotTheMetric(droppedNans,'TSALE',rootDir,mergeIntensities,combineControls,dropNans)
return droppedNans
else:
plotTheMetric(df,'TSALE',rootDir,mergeIntensities, combineControls,dropNans)
return df
## Nans in the PreferenceIndex_P01 (and P10) columns are treated as not existing in the plotting;
## therefore, when I am getting the mean of the two columns, I can't treat them as zeroes.
## This function, first removes all the rows where either PreferenceIndex_P01 OR PreferenceIndex_P10 is Nan,
## then calculates a PreferenceIndex_Mean column to the df.
def MeanPreferenceIndexNoNANs(df):
droppedNans = df.dropna(subset = ['TSALE_P10','TSALE_P01'])
droppedNans = droppedNans.assign(TSALE_Mean_noNan = pd.Series(droppedNans[['TSALE_P01','TSALE_P10']].mean(axis=1), index = droppedNans.index))
droppedNans = droppedNans.reset_index(drop=True)
return droppedNans
# ## Metric: weighted-TSALE
# In[4]:
def weighted_TSALE(dff, rootDir,mergeIntensities, compareLightType, combineControls=False, dropNans=False):
df = TSALE(dff, rootDir,mergeIntensities, combineControls, dropNans)
## empty lists to store the weights for both epochs
weights_P01 = []
weights_P10 = []
numofflies = df.shape[0]
## calculate weights per fly
for i in range(numofflies):
numofFrames_P01 = len(df['InLight_HeadX|P01'][i])
firstContact_P01 = df['First light contact index in P01'][i]
if not pd.isnull(firstContact_P01):
## weight is calculated as: remaining time after the discovery / whole epoch
w_P01 = (numofFrames_P01-firstContact_P01)/float(numofFrames_P01)
weights_P01.append(w_P01)
else:
weights_P01.append(np.nan)
numofFrames_P10 = len(df['InLight_HeadX|P10'][i])
firstContact_P10 = df['First light contact index in P10'][i]
if not pd.isnull(firstContact_P10):
## weight is remaining time after the discovery / whole epoch
w_P10 = (numofFrames_P10-firstContact_P10)/float(numofFrames_P10)
weights_P10.append(w_P10)
else:
weights_P10.append(np.nan)
df = df.assign(weights_P01 = pd.Series(weights_P01, index=df.index),
weights_P10 = pd.Series(weights_P10, index=df.index))
df = df.assign(weighted_TSALE_P01 = pd.Series(df['weights_P01'] * df['TSALE_P01'], index=df.index),
weighted_TSALE_P10 = pd.Series(df['weights_P10'] * df['TSALE_P10'], index=df.index))
df = df.assign(weighted_TSALE_Mean = pd.Series(df[['weighted_TSALE_P01','weighted_TSALE_P10']].mean(axis=1), index=df.index))
plotTheMetric(df,'weighted_TSALE',rootDir,mergeIntensities,combineControls,compareLightType,dropNans)
return df
# ## Metric: Light attraction index
# In[5]:
## Function 1: Detect choice zone entrance/exits indices, store them in the df
## Pass the df to these functions:
## Function 2: Sort and Plot the tracts as in Wilson paper _ this only needs the entrance indices
## Function 2.5: To plot the mean trajactories as in the Wilson paper, need an alignment function. Choice zone borders vary.
## Function 3: Calculate Attraction Index from the exits _ this needs the exit indice, as well as coordination to decide
## whether traversel or reversal.
###!!! Fix HeadX to smoothed headX
def DetectEntraceandExitIndicesToTheChoiceZone(df, choiceZoneWidth_mm = 10, thresholdToExcludeCursorJumps_pix = 20):
## Lists to store the entrance and corresponding exits info per fly for P01 and P10
FromTheWindPortEnd_P01_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX = []
FromTheClosedEnd_P01_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX = []
FromTheWindPortEnd_P10_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX = []
FromTheClosedEnd_P10_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX = []
## Lists to stores choice zone borders per fly
ChoiceZoneBordersPerFly_P01 = []
ChoiceZoneBordersPerFly_P10 = []
numberOfFlies = df.shape[0]
## get the mm to pix coefficient
mmPerPix = df['mmPerPix'][0]
## convert the zone width from mm to pix
choiceZoneWidth_pix = choiceZoneWidth_mm/mmPerPix
for fly in range(0,numberOfFlies):
## one fly can have multiple decisions; I will keep seperate lists per fly
flyDecisionList_theWindPortEnd_P01 = []
flyDecisionList_theClosedEnd_P01 = []
flyDecisionList_theWindPortEnd_P10 = []
flyDecisionList_theClosedEnd_P10 = []
## get border coordinates for the two light events per fly
border_P01 = df.iloc[fly]['Border|P01']
border_P10 = df.iloc[fly]['Border|P10']
## identify the choice zone lef-right borders per chamber, since borders change across chambers, even P01 vs P10
choiceZoneBorders_P01 = [border_P01-choiceZoneWidth_pix/2, border_P01+choiceZoneWidth_pix/2]
choiceZoneBorders_P10 = [border_P10-choiceZoneWidth_pix/2, border_P10+choiceZoneWidth_pix/2]
## store the border info to be attached to the df
ChoiceZoneBordersPerFly_P01.append(choiceZoneBorders_P01)
ChoiceZoneBordersPerFly_P10.append(choiceZoneBorders_P10)
## NTS: In Adam's paper, only when flies enter and exit counted as a decision.
## get the indices where P01 and P10 were taking place
P01_startIndex, P01_endIndex = df.iloc[fly]['LightON index|P01']
P10_startIndex, P10_endIndex = df.iloc[fly]['LightON index|P10']
## get head X coordinates while the light was ON, P01 and P10
headXcoordIn_P01 = df.iloc[fly]['HeadX(pix)_smoothed'][P01_startIndex:P01_endIndex]
headXcoordIn_P10 = df.iloc[fly]['HeadX(pix)_smoothed'][P10_startIndex:P10_endIndex]
## go thru the head X coordinates during the P01 event to find entrances and related exits(if any)
for i in range(len(headXcoordIn_P01)-1):
## if entering to the zone from the wind port end
if (headXcoordIn_P01[i] < choiceZoneBorders_P01[0]) & ((headXcoordIn_P01[i+1] > choiceZoneBorders_P01[0]) & (headXcoordIn_P01[i+1] < choiceZoneBorders_P01[1])):
## store the entrance info [entrance index, entrance coor]
temp = [P01_startIndex+i+1, headXcoordIn_P01[i+1]]
## now detect the exit of this entrance
for j in range(len(headXcoordIn_P01[i:])-1):
if (headXcoordIn_P01[i:][j+1] < choiceZoneBorders_P01[0]) | (headXcoordIn_P01[i:][j+1] > choiceZoneBorders_P01[1]):
## attach the exit to the temp list [entrance index, entrance coor, exit index, exit coor]
temp.append(P01_startIndex+i+j+1)
temp.append(headXcoordIn_P01[i+j+1])
break
flyDecisionList_theWindPortEnd_P01.append(temp)
## found an entrance from the closed end of the chamber
if (headXcoordIn_P01[i] > choiceZoneBorders_P01[1]) & ((headXcoordIn_P01[i+1] < choiceZoneBorders_P01[1]) & (headXcoordIn_P01[i+1] > choiceZoneBorders_P01[0])):
## store the entrance info [entrance index, entrance coor]
temp = [P01_startIndex+i+1, headXcoordIn_P01[i+1]]
## now detect the exit of this entrance, if any
for j in range(len(headXcoordIn_P01[i:])-1):
if (headXcoordIn_P01[i:][j+1] < choiceZoneBorders_P01[0]) | (headXcoordIn_P01[i:][j+1] > choiceZoneBorders_P01[1]):
## attach the exit to the temp list [entrance index, entrance coor, exit index, exit coor]
temp.append(P01_startIndex+i+j+1)
temp.append(headXcoordIn_P01[i+j+1])
break
## add this decision to the list before searching for other decisions of the same fly
flyDecisionList_theClosedEnd_P01.append(temp)
## go thru the head X coordinates during the P10 event to find entrances and related exits(if any)
for i in range(len(headXcoordIn_P10)-1):
## if entering to the zone from the wind port end
if (headXcoordIn_P10[i] < choiceZoneBorders_P10[0]) & ((headXcoordIn_P10[i+1] > choiceZoneBorders_P10[0]) & (headXcoordIn_P10[i+1] < choiceZoneBorders_P10[1])):
## store the entrance info [entrance index, entrance coor]
temp = [P10_startIndex+i+1, headXcoordIn_P10[i+1]]
## now detect the exit of this entrance
for j in range(len(headXcoordIn_P10[i:])-1):
if (headXcoordIn_P10[i:][j+1] < choiceZoneBorders_P10[0]) | (headXcoordIn_P10[i:][j+1] > choiceZoneBorders_P10[1]):
## attach the exit to the temp list [entrance index, entrance coor, exit index, exit coor]
temp.append(P10_startIndex+i+j+1)
temp.append(headXcoordIn_P10[i+j+1])
break
flyDecisionList_theWindPortEnd_P10.append(temp)
## found an entrance from the closed end of the chamber
if (headXcoordIn_P10[i] > choiceZoneBorders_P10[1]) & ((headXcoordIn_P10[i+1] < choiceZoneBorders_P10[1]) & (headXcoordIn_P10[i+1] > choiceZoneBorders_P10[0])):
## store the entrance info [entrance index, entrance coor]
temp = [P10_startIndex+i+1, headXcoordIn_P10[i+1]]
## now detect the exit of this entrance, if any
for j in range(len(headXcoordIn_P10[i:])-1):
if (headXcoordIn_P10[i:][j+1] < choiceZoneBorders_P10[0]) | (headXcoordIn_P10[i:][j+1] > choiceZoneBorders_P10[1]):
## attach the exit to the temp lis, [entrance index, entrance coor, exit index, exit coor]
temp.append(P10_startIndex+i+j+1)
temp.append(headXcoordIn_P10[i+j+1])
break
## add this decision to the list before searching for other decisions of the same fly
flyDecisionList_theClosedEnd_P10.append(temp)
FromTheWindPortEnd_P01_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX.append(flyDecisionList_theWindPortEnd_P01)
FromTheClosedEnd_P01_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX.append(flyDecisionList_theClosedEnd_P01)
FromTheWindPortEnd_P10_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX.append(flyDecisionList_theWindPortEnd_P10)
FromTheClosedEnd_P10_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX.append(flyDecisionList_theClosedEnd_P10)
df = df.assign(ChoiceZoneBordersperFly_P01 = pd.Series(ChoiceZoneBordersPerFly_P01, index=df.index),
ChoiceZoneBordersperFly_P10 = pd.Series(ChoiceZoneBordersPerFly_P10, index=df.index),
FromTheWindPortEnd_P01_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX = pd.Series(FromTheWindPortEnd_P01_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX, index=df.index),
FromTheClosedEnd_P01_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX = pd.Series(FromTheClosedEnd_P01_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX, index=df.index),
FromTheWindPortEnd_P10_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX = pd.Series(FromTheWindPortEnd_P10_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX, index=df.index),
FromTheClosedEnd_P10_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX = pd.Series(FromTheClosedEnd_P10_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX, index=df.index))
return df
def LAI(df, rootDir,mergeIntensities, combineControls=False, dropNans=False):
## Caution: when you are calculating the LAI_Mean, getting the avarage of P01 and P10 may yield different results than
## counting the votes for the two epochs.
## P01 most probably will be excluded due to the conflicting of interpretations when the wind applied.
## So, don't worry too much about the mean LAI.
## LAI does not need to be calculated seperately for down and upwind cases. Combine them together.
## The downwind/upwind will be nice to see in the path-analysis, and number of border crossings.
df = DetectEntraceandExitIndicesToTheChoiceZone(df)
LightAttractionIndex_P01 = []
LightAttractionIndex_P10 = []
# go through all the flies
for fly in range(len(df)):
entrance_exit_log_P01 = []
entrance_exit_log_P10 = []
number_of_light_votes_P01 = 0
number_of_dark_votes_P01 = 0
number_of_light_votes_P10 = 0
number_of_dark_votes_P10 = 0
## combine the choice events for P01 and P10, regardless to which part of the chamber flies entered to the zone
entrance_exit_log_P01.extend(df['FromTheClosedEnd_P01_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX'][fly])
entrance_exit_log_P01.extend(df['FromTheWindPortEnd_P01_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX'][fly])
entrance_exit_log_P10.extend(df['FromTheClosedEnd_P10_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX'][fly])
entrance_exit_log_P10.extend(df['FromTheWindPortEnd_P10_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX'][fly])
## get the choice zone borders per fly to detect whether exit was to light or dark side
border_P01 = df['Border|P01'][fly]
border_P10 = df['Border|P10'][fly]
## go thru the entrances per fly and find out where the exits were made to
## note that the light and dark sides are different sides of the border in each epoch
## for P01
if entrance_exit_log_P01:
for log in entrance_exit_log_P01:
if len(log) == 4:
exit_headX = log[3]
## NTS: using border line, instead of the choice zone borders, to compare the exit headX. Otherwise it
## fucks up.
##exit to the light side
if exit_headX > border_P01:
number_of_light_votes_P01 = number_of_light_votes_P01 + 1
##exit to the dark side
elif exit_headX < border_P01:
number_of_dark_votes_P01 = number_of_dark_votes_P01 + 1
if (number_of_light_votes_P01 + number_of_dark_votes_P01) != 0:
LAI_P01 = (float(number_of_light_votes_P01) - float(number_of_dark_votes_P01))/(float(number_of_light_votes_P01) + float(number_of_dark_votes_P01))
LightAttractionIndex_P01.append(LAI_P01)
else:
LightAttractionIndex_P01.append(np.nan)
else:
LightAttractionIndex_P01.append(np.nan)
## for P10
if entrance_exit_log_P10:
for log in entrance_exit_log_P10:
if len(log) == 4:
exit_headX = log[3]
##exit to the dark side
if exit_headX > border_P10:
number_of_dark_votes_P10 = number_of_dark_votes_P10 + 1
##exit to the light side
elif exit_headX < border_P10:
number_of_light_votes_P10 = number_of_light_votes_P10 + 1
if (number_of_light_votes_P10 + number_of_dark_votes_P10) != 0:
LAI_P10 = (float(number_of_light_votes_P10) - float(number_of_dark_votes_P10))/(float(number_of_light_votes_P10) + float(number_of_dark_votes_P10))
LightAttractionIndex_P10.append(LAI_P10)
else:
LightAttractionIndex_P10.append(np.nan)
else:
LightAttractionIndex_P10.append(np.nan)
df = df.assign(LAI_P01 = pd.Series(LightAttractionIndex_P01, index=df.index),
LAI_P10 = pd.Series(LightAttractionIndex_P10, index=df.index))
df = df.assign(LAI_Mean = pd.Series(df[['LAI_P01','LAI_P10']].mean(axis=1), index=df.index))
plotTheMetric(df,'LAI',rootDir,mergeIntensities,combineControls,dropNans)
return None
# ## Metrix: Reversal PI
# In[6]:
def RPI(df, rootDir,mergeIntensities, combineControls=False, dropNans=False):
df = DetectEntraceandExitIndicesToTheChoiceZone(df)
ReversalPI_P01 = []
ReversalPI_P10 = []
# go through all the flies
for fly in range(len(df)):
entrance_exit_log_P01 = []
entrance_exit_log_P10 = []
number_of_light_reversals_P01 = 0
number_of_dark_reversals_P01 = 0
number_of_light_reversals_P10 = 0
number_of_dark_reversals_P10 = 0
## Use both the wind port and closed end entrances
entrance_exit_log_P01.extend(df['FromTheClosedEnd_P01_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX'][fly])
entrance_exit_log_P01.extend(df['FromTheWindPortEnd_P01_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX'][fly])
entrance_exit_log_P10.extend(df['FromTheClosedEnd_P10_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX'][fly])
entrance_exit_log_P10.extend(df['FromTheWindPortEnd_P10_EnterIdx_EnterHeadX_ExitIdx_ExitHeadX'][fly])
## get the border lines per fly to detect whether exit was to light or dark side
border_P01 = df['Border|P01'][fly]
border_P10 = df['Border|P10'][fly]
## go thru the entrances per fly and find out where the exits were made to
## note that the light and dark sides are different sides of the border in each epoch
## for P01
if entrance_exit_log_P01:
for log in entrance_exit_log_P01:
if len(log) == 4:
enter_headX = log[1]
exit_headX = log[3]
##came from to the dark side, returned to the dark side
if (enter_headX < border_P01) & (exit_headX < border_P01):
number_of_dark_reversals_P01 = number_of_dark_reversals_P01 + 1
##came from the lit side, returned to the lit side
elif (enter_headX > border_P01) & (exit_headX > border_P01):
number_of_light_reversals_P01 = number_of_light_reversals_P01 + 1
if (number_of_dark_reversals_P01 + number_of_light_reversals_P01) != 0:
RPI_P01 = (float(number_of_light_reversals_P01) - float(number_of_dark_reversals_P01))/(float(number_of_light_reversals_P01) + float(number_of_dark_reversals_P01))
ReversalPI_P01.append(RPI_P01)
else:
ReversalPI_P01.append(np.nan)
else:
ReversalPI_P01.append(np.nan)
## for P10
if entrance_exit_log_P10:
for log in entrance_exit_log_P10:
if len(log) == 4:
enter_headX = log[1]
exit_headX = log[3]
##came from light, returned to the lit side
if (enter_headX < border_P10) & (exit_headX < border_P10):
number_of_light_reversals_P10 = number_of_light_reversals_P10 + 1
##came from the dark half, returned to the dark half
elif (enter_headX > border_P10) & (exit_headX > border_P10):
number_of_dark_reversals_P10 = number_of_dark_reversals_P10 + 1
if (number_of_dark_reversals_P10 + number_of_light_reversals_P10) != 0:
RPI_P10 = (float(number_of_light_reversals_P10) - float(number_of_dark_reversals_P10))/(float(number_of_dark_reversals_P10) + float(number_of_light_reversals_P10))
ReversalPI_P10.append(RPI_P10)
else:
ReversalPI_P10.append(np.nan)
else:
ReversalPI_P10.append(np.nan)
df = df.assign(RPI_P01 = pd.Series(ReversalPI_P01, index=df.index),
RPI_P10 = pd.Series(ReversalPI_P10, index=df.index))
df = df.assign(RPI_Mean = pd.Series(df[['RPI_P01','RPI_P10']].mean(axis=1), index=df.index))
plotTheMetric(df,'RPI',rootDir,mergeIntensities,combineControls,dropNans)
return None
# ## Metric: Number of Border Crossings
# In[7]:
### NTS: fix this to SMOOTHED HEAD X!!
def NoBC(df, rootDir, mergeIntensities,combineControls=False, dropNans=False):
## lists to keep the metric for each fly
list_of_number_of_border_crossings_P01 = []
list_of_number_of_border_crossings_P10 = []
for fly in range(len(df)):
## get the P01 and P10 epoch indices
start_of_P01 = df['LightON index|P01'][fly][0]
end_of_P01 = df['LightON index|P01'][fly][1]
start_of_P10 = df['LightON index|P10'][fly][0]
end_of_P10 = df['LightON index|P10'][fly][1]
## get the head X positions during the epochs
headX_during_P01 = df['HeadX(pix)_smoothed'][fly][start_of_P01:end_of_P01]
headX_during_P10 = df['HeadX(pix)_smoothed'][fly][start_of_P10:end_of_P10]
## get the border corrdinates
border_P01 = df['Border|P01'][fly]
border_P10 = df['Border|P10'][fly]
## values to keep the crossings for each fly
number_of_border_crossings_P01 = 0
number_of_border_crossings_P10 = 0
## go thru the headX coords and detect border crossings
## for P01 epoch
for i in range(len(headX_during_P01)-1):
current_coor = headX_during_P01[i]
next_coor = headX_during_P01[i+1]
if (current_coor > border_P01) & (next_coor < border_P01):
number_of_border_crossings_P01 = number_of_border_crossings_P01 + 1
elif (current_coor < border_P01) & (next_coor > border_P01):
number_of_border_crossings_P01 = number_of_border_crossings_P01 + 1
list_of_number_of_border_crossings_P01.append(number_of_border_crossings_P01)
## go thru the headX coords and detect border crossings
## for P10 epoch
for i in range(len(headX_during_P10)-1):
current_coor = headX_during_P10[i]
next_coor = headX_during_P10[i+1]
if (current_coor > border_P10) & (next_coor < border_P10):
number_of_border_crossings_P10 = number_of_border_crossings_P10 + 1
elif (current_coor < border_P10) & (next_coor > border_P10):
number_of_border_crossings_P10 = number_of_border_crossings_P10 + 1
list_of_number_of_border_crossings_P10.append(number_of_border_crossings_P10)
df = df.assign(NoBC_P01 = pd.Series(list_of_number_of_border_crossings_P01, index=df.index),
NoBC_P10 = pd.Series(list_of_number_of_border_crossings_P10, index=df.index))
df = df.assign(NoBC_Mean = pd.Series(df[['NoBC_P01','NoBC_P10']].mean(axis=1), index=df.index))
plotTheMetric(df,'NoBC',rootDir,mergeIntensities,combineControls,dropNans)
return None
# ## Metric: Speed ratio
# In[8]:
### NTS: convert HeadX to SMOOTHED HEADX
## 1. detect the chunks of headX that were in the epoch regions for before_the_light_P01, during_the_light_P01..
## 2. calculate total distance travelled and total number of frames
## 3. convert them into mm and sec
## 4. calculate the ratio
def calculateSpeed(data, fps, mmPerPixel):
number_of_frames = 0
total_distance_pixel = 0
## Go thru the chunks of contuniued headX coordinates
for sublist in data:
for distance in sublist:
total_distance_pixel = total_distance_pixel + distance
number_of_frames = number_of_frames + 1
if (number_of_frames != 0) & (total_distance_pixel != 0):
total_time_sec = float(number_of_frames) / float(fps)
total_distance_mm = total_distance_pixel * mmPerPixel
speed_pix_per_frame = float(total_distance_pixel)/float(number_of_frames)
speed_mm_per_sec = float(total_distance_mm)/float(total_time_sec)
else:
speed_pix_per_frame = np.nan
speed_mm_per_sec = np.nan
return speed_mm_per_sec
def Log2SpeedRatio(df ,rootDir,mergeIntensities, combineControls=False, dropNans=False):
list_of_log2_speed_ratio_P01 = []
list_of_log2_speed_ratio_P10 = []
for fly in range(len(df)):
## get the light ON indices to detect before and during light episodes in an experiment
lightON_P01 = df['LightON index|P01'][fly]
lightON_P10 = df['LightON index|P10'][fly]
## get the borders
border_P01 = df['Border|P01'][fly]
border_P10 = df['Border|P01'][fly]
## get fps and mmPerPixel for speed calculation
fps = df['fps'][fly]
mmPerPixel = df['mmPerPix'][fly]
## get the fly's headX for the entire exp
fly_headX_coords = df['HeadX(pix)_smoothed'][fly]
## chop up the headX into the episodes
before_the_light_P01_headX = fly_headX_coords[:lightON_P01[0]]
during_the_light_P01_headX = fly_headX_coords[lightON_P01[0]:lightON_P01[1]]
before_the_light_P10_headX = fly_headX_coords[lightON_P01[1]:lightON_P10[0]]
during_the_light_P10_headX = fly_headX_coords[lightON_P10[0]:lightON_P10[1]]
## lists to keep the chunks (lists) of headX there were in the region that the light was going to be turned ON
before_the_light_P01_headX_in_the_region = []
during_the_light_P01_headX_in_the_region = []
before_the_light_P10_headX_in_the_region = []
during_the_light_P10_headX_in_the_region = []
## keep the indices of headX where they are in the region of interest
## for P01
before_the_light_P01_headX_temp = []
for i in range(len(before_the_light_P01_headX)):
if before_the_light_P01_headX[i] > border_P01:
before_the_light_P01_headX_temp.append(i)
during_the_light_P01_headX_temp = []
for i in range(len(during_the_light_P01_headX)):
if during_the_light_P01_headX[i] > border_P01:
during_the_light_P01_headX_temp.append(i)
## for P10
before_the_light_P10_headX_temp = []
for i in range(len(before_the_light_P10_headX)):
if before_the_light_P10_headX[i] < border_P10:
before_the_light_P10_headX_temp.append(i)
during_the_light_P10_headX_temp = []
for i in range(len(during_the_light_P10_headX)):
if during_the_light_P10_headX[i] < border_P10:
during_the_light_P10_headX_temp.append(i)
## chop up the indices' lists and find consecutives
for k, g in groupby(enumerate(before_the_light_P01_headX_temp), lambda (i,x):i-x):
sublist = map(itemgetter(1), g)
if len(sublist) > 1:
before_the_light_P01_headX_in_the_region.append(sublist)
for k, g in groupby(enumerate(during_the_light_P01_headX_temp), lambda (i,x):i-x):
sublist = map(itemgetter(1), g)
if len(sublist) > 1:
during_the_light_P01_headX_in_the_region.append(sublist)
for k, g in groupby(enumerate(before_the_light_P10_headX_temp), lambda (i,x):i-x):
sublist = map(itemgetter(1), g)
if len(sublist) > 1:
before_the_light_P10_headX_in_the_region.append(sublist)
for k, g in groupby(enumerate(during_the_light_P10_headX_temp), lambda (i,x):i-x):
sublist = map(itemgetter(1), g)
if len(sublist) > 1:
during_the_light_P10_headX_in_the_region.append(sublist)
## By using the index lists, create distance travelled lists of lists.
## For P01
before_the_light_P01_headX_in_the_region_distance_travelled = []
for l in before_the_light_P01_headX_in_the_region:
start_idx = l[0]
end_idx = l[-1]
temp = []
for i in range(start_idx,end_idx):
diff = abs(before_the_light_P01_headX[i+1] - before_the_light_P01_headX[i])
temp.append(diff)
before_the_light_P01_headX_in_the_region_distance_travelled.append(temp)
during_the_light_P01_headX_in_the_region_distance_travelled = []
for l in during_the_light_P01_headX_in_the_region:
start_idx = l[0]
end_idx = l[-1]
temp = []
for i in range(start_idx,end_idx):
diff = abs(during_the_light_P01_headX[i+1] - during_the_light_P01_headX[i])
temp.append(diff)
during_the_light_P01_headX_in_the_region_distance_travelled.append(temp)
## for P10
before_the_light_P10_headX_in_the_region_distance_travelled = []
for l in before_the_light_P10_headX_in_the_region:
start_idx = l[0]
end_idx = l[-1]
temp = []
for i in range(start_idx,end_idx):
diff = abs(before_the_light_P10_headX[i+1] - before_the_light_P10_headX[i])
temp.append(diff)
before_the_light_P10_headX_in_the_region_distance_travelled.append(temp)
during_the_light_P10_headX_in_the_region_distance_travelled = []
for l in during_the_light_P10_headX_in_the_region:
start_idx = l[0]
end_idx = l[-1]
temp = []
for i in range(start_idx,end_idx):
diff = abs(during_the_light_P10_headX[i+1] - during_the_light_P10_headX[i])
temp.append(diff)
during_the_light_P10_headX_in_the_region_distance_travelled.append(temp)
## Send the distance travelled lists to the calculateSpeed function to get an average speed (mm/sec)
speed_before_the_light_P01_headX_in_the_region = calculateSpeed(before_the_light_P01_headX_in_the_region_distance_travelled, fps, mmPerPixel)
speed_during_the_light_P01_headX_in_the_region = calculateSpeed(during_the_light_P01_headX_in_the_region_distance_travelled, fps, mmPerPixel)
speed_before_the_light_P10_headX_in_the_region = calculateSpeed(before_the_light_P10_headX_in_the_region_distance_travelled, fps, mmPerPixel)
speed_during_the_light_P10_headX_in_the_region = calculateSpeed(during_the_light_P10_headX_in_the_region_distance_travelled, fps, mmPerPixel)
## Calculate the speed ratios for P01 and P10
speed_ratio_P01 = speed_during_the_light_P01_headX_in_the_region / speed_before_the_light_P01_headX_in_the_region
speed_ratio_P10 = speed_during_the_light_P10_headX_in_the_region / speed_before_the_light_P10_headX_in_the_region
## Get and Store the log2 of the ratios
log2_speed_ratio_P01 = math.log(speed_ratio_P01, 2.0)
log2_speed_ratio_P10 = math.log(speed_ratio_P10, 2.0)