-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExploratory Analysis.py
More file actions
1701 lines (1221 loc) · 63.8 KB
/
Exploratory Analysis.py
File metadata and controls
1701 lines (1221 loc) · 63.8 KB
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
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import math
import datetime
import matplotlib
import os
import plotly.graph_objects as go
import itertools
from scipy.stats import pearsonr
import plotly.express as px
# In[2]:
#x_2012, y_2012, tms_2012 were part of RData file which was read and converted to .csv.
#All data files are uploaded in the Data directory.
#x & y are dataframes each with 1471015 rows, 26 columns. Columns are named 'V1', 'V2', ..., 'V26' and correspond to
#the 26 baboons. Each cell contains the x (or y) position of a baboon at a particular timestamp. Timestamps are stored in tms.
y = pd.read_csv("y_2012.csv")
x = pd.read_csv("x_2012.csv")
#tms is a dataframe with 1471015 rows, 1 column. Each row contains a timestamp, and the index directly corresponds to the
#index of x and y. The column is named 'x'.
tms = pd.read_csv("tms_2012.csv")
#demo contains age, sex, etc. information for each baboon
demo = pd.read_csv('IDs_2012.csv')
# In[4]:
#look at the first five rows of x, y and tms:
print(f'X: \n{x.head()}\n')
print(f'Y: \n{y.head()}\n')
print(f'tms: \n{tms.head()}')
# In[3]:
#When data is read from csv to pandas dataframe, it is read as string by default. The following line converts the
#strings to datetime format (the 'pd.to_datetime' part), and add three hours to it to convert to East Africa Local time
#(the '+ pd.to_timedelta(...' part)
tms['x'] = pd.to_datetime(tms['x']) + pd.to_timedelta(([3] * len(tms)), unit = 'h')
#dates is a dataframe containing all the dates from the dataset
dates = pd.DataFrame(pd.to_datetime(tms['x']).dt.date)
#The next three lines are three lists initialized to be empty. These would contain one dataframe for each date.
#Essentially, x, y and tms are being broken up from one long dataframe spanning ~35 days into smaller dataframes spanning 1 day.
x_days_full = []
y_days_full = []
tms_days_full = []
for day in dates.x.unique():
ind = dates[dates['x'] == day].index.to_list()
x_i = x.iloc[ind]
y_i = y.iloc[ind]
tms_i = tms.iloc[ind]
x_days_full.append(x_i)
y_days_full.append(y_i)
tms_days_full.append(tms_i)
# In[4]:
#The next task is to temporally discretize each day to contain 1 data point every 10 seconds instead of one every second.
#As an example, consider the first day and and see how it looks
#after resampling every 10 seconds. The dataframe of 43143 rows was reduced to 4315 rows.
t = tms_days_full[0][tms_days_full[0].index % 10 == 0]
print(f'{len(tms_days_full[0])} -> {len(t)}')
t
x_days_full[0].loc[t.index]
# In[5]:
import math
#Discretize every day's data
x_days = []
y_days = []
tms_days = []
for day in range(len(tms_days_full)):
t = tms_days_full[day][tms_days_full[day].index % 10 == 0]
x_days.append(x_days_full[day].loc[t.index].reset_index(drop = True))
y_days.append(y_days_full[day].loc[t.index].reset_index(drop = True))
tms_days.append(t.reset_index(drop = True))
# In[59]:
#Get a sense of how many baboons have data for how many days
fig = go.Figure()
counts = []
baboons_with_data = []
for day in range(35):
b = []
c = 0
for baboon in x_days_full[day].columns:
if baboon == 'centroid1':
c += 0
if len(x_days_full[day][x_days_full[day][baboon].notnull()]) > 0:
c += 1
b.append(baboon)
counts.append(c)
baboons_with_data.append(b)
s = set(baboons_with_data[0])
for day in range(len(baboons_with_data)):
if day > 0:
s = s.intersection(set(baboons_with_data[day]))
print(f"Baboons that have data on all 35 days: {s}")
fig.add_trace(go.Scatter(name = f'{day}.{baboon}', x=list(range(35)), y=counts,
mode='lines', marker = dict(size = 2)))
fig.update_layout(title = 'Number of Baboons with Non Null data (2012)',
xaxis_title='Day',
yaxis_title='Number of Baboons')
fig.show()
# In[6]:
#For analysis, we will discard the last and second last day of available data for each baboon.
#second_last_day_available is a dictionary that stores the second last day of each baboon. A dictionary is a mapping of
#key: value pairs. In this case the keys are the baboons, and the values are the second last day of available data that the
#following loop accomplishes.
second_last_day_available = {}
for baboon in x_days_full[0].columns:
for day in range(len(tms_days_full) - 1):
not_null_indices = x_days_full[day+1][x_days_full[day+1][baboon].notnull()].index
if len(not_null_indices) == 0 or day == len(tms_days_full) - 2:
second_last_day_available[baboon] = day
break
# In[7]:
# for day in range(len(tms_2min)):
# dis = []
# no_data = []
# centroids_x_full = pd.DataFrame(x_days[day].mean(axis = 1))
# centroids_y_full = pd.DataFrame(y_days[day].mean(axis = 1))
# x_days[day]['centroid1'] = centroids_x_full
# y_days[day]['centroid1'] = centroids_y_full
# In[7]:
#Interpolate Nans in the data. There might be some warnings displayed while executing this section-- that can be ignored.
#This takes about 20 seconds to run.
from scipy.interpolate import griddata
interpolated_x_days = []
interpolated_y_days = []
for day in range(len(tms_days)):
x_ = pd.DataFrame()
y_ = pd.DataFrame()
print(day)
for baboon in x_days[day].columns: #[x for x in x_days[day].columns if x != 'dist']:
# print(baboon)
data = [x_days[day][baboon], y_days[day][baboon]]
headers = ["x", "y"]
data = pd.concat(data, axis=1, keys=headers)
restore_index = data.index
data.index = pd.to_datetime(tms_days[day]['x'])
not_null_indices = data[data['x'].notnull()].index
if len(not_null_indices) > 0:
l1 = min(not_null_indices)
l2 = max(not_null_indices)
to_interpolate = data[(data.index >= l1) & (data.index <= l2)]
to_interpolate.resample('D').mean()
to_interpolate['x_i'] = to_interpolate['x'].interpolate()
to_interpolate['y_i'] = to_interpolate['y'].interpolate()
x_col = pd.concat([data[data.index < l1], to_interpolate, data[data.index > l2]], axis = 0)['x_i']
x_col = x_col.rename(baboon)
y_col = pd.concat([data[data.index < l1], to_interpolate, data[data.index > l2]], axis = 0)['y_i']
y_col = y_col.rename(baboon)
else:
x_col = data['x']
y_col = data['y']
x_col = x_col.rename(baboon)
y_col = y_col.rename(baboon)
x_ = pd.concat([x_, x_col], axis = 1)
y_ = pd.concat([y_, y_col], axis = 1)
x_.index = restore_index
y_.index = restore_index
interpolated_x_days.append(x_)
interpolated_y_days.append(y_)
# In[8]:
#Compute the group centroids at every timestamp every day
for day in range(len(tms_days)):
dis = []
no_data = []
# print(day)
centroids_x = pd.DataFrame(interpolated_x_days[day].mean(axis = 1))
centroids_y = pd.DataFrame(interpolated_y_days[day].mean(axis = 1))
interpolated_x_days[day]['centroid1'] = centroids_x
interpolated_y_days[day]['centroid1'] = centroids_y
interpolated_x_days
# In[10]:
#In this part, we will calculate the spots where the baboons started from and returned to on each day for each baboon.
#For baboon B on day D, we will average the first 10 non-null coordinates of B on day D and label that at the position from
#where they started. This will also be the spot where they would spend the night on day D-1, except on the last day of the
#dataset. For the last day, the return site is simply the point where they were last found.
#first_found_x (y) and last_found_x (y) are nested lists. Each element of first_found_x (y) and last_found_x (y)
#is a list corresponding to a day, containing the positions for each baboon.
first_found_x = []
first_found_y = []
last_found_x = []
last_found_y = []
for day in range(len(tms_days)):
ffx = []
ffy = []
for baboon in [x for x in interpolated_x_days[day].columns if x != 'centroid1']:
not_null_indices = interpolated_x_days[day][interpolated_x_days[day][baboon].notnull()].index
if len(not_null_indices) == 0:
ffx.append(0)
ffy.append(0)
else:
sx = 0
sy = 0
ct = 0
for i in range(10):
if i <= len(not_null_indices):
sx += interpolated_x_days[day].loc[not_null_indices.to_list()[i], baboon]
# print(sx)
sy += interpolated_y_days[day].loc[not_null_indices.to_list()[i], baboon]
ct += 1
# print(ct)
ffx.append(sx/ct)
ffy.append(sy/ct)
first_found_x.append(ffx)
first_found_y.append(ffy)
for day in range(len(tms_days)):
lfx = []
lfy = []
b = 0
for baboon in [x for x in interpolated_x_days[day].columns if x != 'centroid1']:
not_null_indices = interpolated_x_days[day][interpolated_x_days[day][baboon].notnull()].index
if len(not_null_indices) == 0:
lfx.append(0)
lfy.append(0)
else:
if day < len(tms_days) - 1:
not_null_indices_next = interpolated_x_days[day + 1][interpolated_x_days[day + 1][baboon].notnull()].index
lfx.append(first_found_x[day+1][b])
lfy.append(first_found_y[day+1][b])
# if len(not_null_indices_next) > 0:
# lfx.append(first_found_x[day+1][b])
# lfy.append(first_found_y[day+1][b])
# else:
# lfx.append(interpolated_x_days[day].loc[max(not_null_indices), baboon])
# lfy.append(interpolated_y_days[day].loc[max(not_null_indices), baboon])
else:
lfx.append(interpolated_x_days[day].loc[max(not_null_indices), baboon])
lfy.append(interpolated_y_days[day].loc[max(not_null_indices), baboon])
b += 1
last_found_x.append(lfx)
last_found_y.append(lfy)
# In[12]:
#This section takes about an hour to run.
#Each of distances, distances_from_start, distances_from_return and discrete_distances contain an element for every day.
#The daily elements will be dictionaries, with baboons (including centroid) as keys and dataframes of [time, dist] as the values.
'''
distances = [] #contains the distances travelled every 5 minutes, with a sliding window of 10 seconds.
distances_from_start = [] #contains the distances the baboons are at from where they started
distances_from_return = [] #contains the distances the baboons are at from where they would return to
discrete_distances = [] #This contains the distances travelled every 10 seconds, with no sliding window. Used in a plot later.
for day in range(len(tms_days)):
#initializing empty dictionaries to be appended to the lists
d = {}
d2 = {}
d3 = {}
d4 = {}
b = 0 #Will be used to access first_found and last_found positions
print(day)
for baboon in interpolated_x_days[day].columns:
if baboon != 'centroid1' and day >= second_last_day_available[baboon]: #We don't want data for an individual past their second_last day
b += 1
continue
#notnull contains all the indices with non-null data on this day for this baboon
notnull = interpolated_x_days[day][interpolated_x_days[day][baboon].notnull()].index
#initializing the dataframes that would be values for this baboon in the distionaries
df = pd.DataFrame(columns = ['time', 'distance'])
df2 = pd.DataFrame(columns = ['time', 'distance'])
df3 = pd.DataFrame(columns = ['time', 'distance'])
df4 = pd.DataFrame(columns = ['time', 'distance'])
if len(notnull) > 0:
if baboon == 'centroid1':
startx_ = interpolated_x_days[day].loc[notnull[0], baboon]
starty_ = interpolated_y_days[day].loc[notnull[0], baboon]
r_startx = interpolated_x_days[day].loc[notnull[len(notnull) -1], baboon]
r_starty = interpolated_y_days[day].loc[notnull[len(notnull) -1], baboon]
else:
startx_ = first_found_x[day][b]
starty_ = first_found_y[day][b]
r_startx = last_found_x[day][b]
r_starty = last_found_y[day][b]
initial_x = startx_
initial_y = starty_
r_initial_x = r_startx
r_initial_y = r_starty
d_from_start = 0
for i in range(len(notnull)):
ind = notnull[i]
currentx = interpolated_x_days[day].loc[ind, baboon]
currenty = interpolated_y_days[day].loc[ind, baboon]
if i+30 <= len(notnull)-1: #Since the dataset is 10 second discretized, rows every 30 index are 5 minutes apart
#The if stateent checks if the row 5 minute away from the current row is outside the dataset. if not,
#designate the end index to be the index 5 minutes away from the current one.
end_ind = notnull[i + 30]
else:
#otherwise, designate the end index as the last available index with non null data.
end_ind = notnull[len(notnull) - 1]
df.loc[i, 'time'] = tms_days[day].loc[ind, 'x']
df2.loc[i, 'time'] = tms_days[day].loc[ind, 'x']
df3.loc[i, 'time'] = tms_days[day].loc[ind, 'x']
df4.loc[i, 'time'] = tms_days[day].loc[ind, 'x']
endx = interpolated_x_days[day].loc[end_ind, baboon]
endy = interpolated_y_days[day].loc[end_ind, baboon]
dist = ((currentx - endx) ** 2 + (currenty - endy) ** 2) ** 0.5
discrete_dist = ((startx_ - currentx) ** 2 + (starty_ - currenty) ** 2) ** 0.5
d_from_start = ((initial_x - currentx) ** 2 + (initial_y - currenty) ** 2) ** 0.5
d_from_r = ((r_initial_x - currentx) ** 2 + (r_initial_y - currenty) ** 2) ** 0.5
df.loc[i, 'distance'] = dist
df2.loc[i, 'distance'] = d_from_start
df3.loc[i, 'distance'] = d_from_r
df4.loc[i, 'distance'] = discrete_dist
startx_ = currentx
starty_ = currenty
d[baboon] = df
d2[baboon] = df2
d3[baboon] = df3
d4[baboon] = df4
b += 1
distances.append(d)
distances_from_start.append(d2)
distances_from_return.append(d3)
discrete_distances.append(d4)
'''
# In[11]:
#Write distances to files, and read from file so that it won't take an hour to run.
folder1 = "Distances"
folder2 = "Distances from start"
folder3 = "Distances from return"
folder4 = "Discrete distances"
parent_dir = r"C:\Namrata\OSU\Summer21\baboon"
path1 = os.path.join(parent_dir, folder1)
path2 = os.path.join(parent_dir, folder2)
path3 = os.path.join(parent_dir, folder3)
path4 = os.path.join(parent_dir, folder4)
try:
os.mkdir(path1)
os.mkdir(path2)
os.mkdir(path3)
os.mkdir(path4)
except FileExistsError:
True
# In[27]:
'''
for day in range(len(tms_days)):
for b in list(distances[day].keys()):
f1 = open(f"{path1}/Day{day+1}Baboon{b}Distances.csv", 'w', newline = '')
dist_to_write1 = distances[day][b]
dist_to_write1.to_csv(f1, index = False)
f1.close()
for day in range(len(tms_days)):
for b in list(distances_from_start[day].keys()):
f2 = open(f"{path2}/Day{day+1}Baboon{b}Distances from start.csv", 'w', newline = '')
dist_to_write2 = distances_from_start[day][b]
dist_to_write2.to_csv(f2, index = False)
f2.close()
for day in range(len(tms_days)):
for b in list(distances_from_return[day].keys()):
f3 = open(f"{path3}/Day{day+1}Baboon{b}Distances from return.csv", 'w', newline = '')
dist_to_write3 = distances_from_return[day][b]
dist_to_write3.to_csv(f3, index = False)
f3.close()
for day in range(len(tms_days)):
for b in list(discrete_distances[day].keys()):
f4 = open(f"{path4}/Day{day+1}Baboon{b}Discrete distances.csv", 'w', newline = '')
dist_to_write4 = discrete_distances[day][b]
dist_to_write4.to_csv(f4, index = False)
f4.close()
'''
distances1 = [] #contains the distances travelled every 5 minutes, with a sliding window of 10 seconds.
distances_from_start1 = [] #contains the distances the baboons are at from where they started
distances_from_return1 = [] #contains the distances the baboons are at from where they would return to
discrete_distances1 = [] #This contains the distances travelled every 10 seconds, with no sliding window. Used in a plot later.
for day in range(len(tms_days)):
d = {}
for b in interpolated_x_days[day].columns:
try:
dtypes = {'time': 'str', 'distance': 'float'}
d[b] = pd.read_csv(f"{path1}/Day{day+1}Baboon{b}Distances.csv", dtype=dtypes, parse_dates=['time'])
except FileNotFoundError:
continue
distances1.append(d)
for day in range(len(tms_days)):
d = {}
for b in interpolated_x_days[day].columns:
try:
dtypes = {'time': 'str', 'distance': 'float'}
d[b] = pd.read_csv(f"{path2}/Day{day+1}Baboon{b}Distances from start.csv", dtype=dtypes, parse_dates=['time'])
except FileNotFoundError:
continue
distances_from_start1.append(d)
for day in range(len(tms_days)):
d = {}
for b in interpolated_x_days[day].columns:
try:
dtypes = {'time': 'str', 'distance': 'float'}
d[b] = pd.read_csv(f"{path3}/Day{day+1}Baboon{b}Distances from return.csv", dtype=dtypes, parse_dates=['time'])
except FileNotFoundError:
continue
distances_from_return1.append(d)
for day in range(len(tms_days)):
d = {}
for b in interpolated_x_days[day].columns:
try:
dtypes = {'time': 'str', 'distance': 'float'}
d[b] = pd.read_csv(f"{path4}/Day{day+1}Baboon{b}Discrete distances.csv", dtype=dtypes, parse_dates=['time'])
except FileNotFoundError:
continue
discrete_distances1.append(d)
# In[13]:
#distances_from_start and distances_from_return in the previous section contained the straight line distances.
#Here, we calculate the actual distances travelled, using the discrete_distances
'''
distances_from_start_new = []
distances_from_return_new = []
for day in range(len(tms_days)):
print(day)
d2 = {}
d3 = {}
b = 0
for baboon in interpolated_x_days[day].columns:
if baboon != 'centroid1' and day >= second_last_day_available[baboon]:
b += 1
continue
notnull = interpolated_x_days[day][interpolated_x_days[day][baboon].notnull()].index
df2 = pd.DataFrame(columns = ['time', 'distance'])
df3 = pd.DataFrame(columns = ['time', 'distance'])
if len(notnull) > 0:
for i in range(len(notnull)):
ind = notnull[i]
df2.loc[i, 'time'] = tms_days[day].loc[ind, 'x']
ind2 = notnull[len(notnull) - i - 1,]
df3.loc[len(notnull) - i - 1, 'time'] = tms_days[day].loc[ind2, 'x']
if i > 0:
df2.loc[i, 'distance'] = df2.loc[i-1, 'distance'] + discrete_distances[day][baboon].loc[i, 'distance']
else:
df2.loc[i, 'distance'] = discrete_distances[day][baboon].loc[i, 'distance']
if i > 0:
df3.loc[len(notnull) - i - 1, 'distance'] = df3.loc[len(notnull) - i, 'distance'] + discrete_distances[day][baboon].loc[len(notnull) - i - 1, 'distance']
else:
df3.loc[len(notnull) - i - 1, 'distance'] = discrete_distances[day][baboon].loc[len(notnull) - i - 1, 'distance']
d2[baboon] = df2
d3[baboon] = df3
distances_from_start_new.append(d2)
distances_from_return_new.append(d3)
'''
# In[13]:
folder5 = "Distances from start new"
folder6 = "Distances from return new"
parent_dir = r"C:\Namrata\OSU\Summer21\baboon"
path5 = os.path.join(parent_dir, folder5)
path6 = os.path.join(parent_dir, folder6)
try:
os.mkdir(path5)
os.mkdir(path6)
except FileExistsError:
True
# In[28]:
#Write distances to files, and read from file so that it won't take an hour to run.
'''
for day in range(len(tms_days)):
for b in list(distances_from_start_new[day].keys()):
f5 = open(f"{path5}/Day{day+1}Baboon{b}Distances from start new.csv", 'w', newline = '')
dist_to_write5 = distances_from_start_new[day][b]
dist_to_write5.to_csv(f5, index = False)
f5.close()
for day in range(len(tms_days)):
for b in list(distances_from_return_new[day].keys()):
f6 = open(f"{path6}/Day{day+1}Baboon{b}Distances from return new.csv", 'w', newline = '')
dist_to_write6 = distances_from_return_new[day][b]
dist_to_write6.to_csv(f6, index = False)
f6.close()
'''
distances_from_start_new1 = [] #contains the distances the baboons are at from where they started
distances_from_return_new1 = [] #contains the distances the baboons are at from where they would return to
for day in range(len(tms_days)):
d = {}
for b in interpolated_x_days[day].columns:
try:
dtypes = {'time': 'str', 'distance': 'float'}
d[b] = pd.read_csv(f"{path5}/Day{day+1}Baboon{b}Distances from start new.csv", dtype=dtypes, parse_dates=['time'])
except FileNotFoundError:
continue
distances_from_start_new1.append(d)
for day in range(len(tms_days)):
d = {}
for b in interpolated_x_days[day].columns:
try:
dtypes = {'time': 'str', 'distance': 'float'}
d[b] = pd.read_csv(f"{path6}/Day{day+1}Baboon{b}Distances from return new.csv", dtype=dtypes, parse_dates=['time'])
except FileNotFoundError:
continue
distances_from_return_new1.append(d)
# In[90]:
#do all baboons have the same length of distances for all days? No
# for day in range(len(tms_2min)):
# centroid = len(distances[day]['centroid1'])
# for baboon in x_2min[day].columns:
# try:
# if len(distances[day][baboon]) != centroid:
# print(day, baboon, len(distances[day][baboon]), centroid)
# except KeyError:
# continue
# In[15]:
#The following section is to find the start times and return times.
from scipy.signal import find_peaks
import numpy as np
peak1 = [] #list of dictionaries, one for each day. each dictionary contains start times for all baboons
peak2 = [] #Structure same as peak1, except this contains return times instead of start times.
for day in range(len(tms_days)):
p1 = {}
p2 = {}
for baboon in interpolated_x_days[day].columns:
if baboon != 'centroid1' and day >= second_last_day_available[baboon]:
continue
if len(distances1[day][baboon]) <= 3000:
continue
first = min(distances1[day][baboon].index)
last = max(distances1[day][baboon].index)
half = math.floor((last - first)/2)
one_third = math.floor((last - first)/3)
two_third = math.floor((last - first)*2/3)
df1 = distances1[day][baboon].loc[first : one_third]
df2 = distances1[day][baboon].loc[two_third : last]
y1 = df1.set_index(df1['time'])
del y1['time']
y1 = np.asarray(y1['distance'])
peaks, properties = find_peaks(y1, height = y1[np.argsort(y1)[-3]], prominence=1, width=1)
if len(peaks) == 0:
peaks, properties = find_peaks(y1, height = y1[np.argsort(y1)[-3]], prominence=0, width=0)
if len(peaks) > 1:
peaks = np.array(peaks[-1])
for key in properties:
properties[key] = np.array(properties[key][0])
print(properties["left_ips"])
if properties["left_ips"].size > 0:
p1[baboon] = math.floor(properties["left_ips"])
y2 = df2.set_index(df2['time'])
del y2['time']
y2 = np.asarray(y2['distance'])
peaks2, properties2 = find_peaks(y2, height = max(y2), prominence=1, width=1) # changed y2[np.argsort(y2)[-3]] to max(y2) to fix day 3 (2) in baboons late/early plot
if len(peaks2) == 0:
peaks2, properties2 = find_peaks(y2, height = y2[np.argsort(y2)[-3]], prominence=0, width=0)
if len(peaks2) > 1:
peaks2 = np.array(peaks2[-1])
for key in properties2:
properties2[key] = np.array(properties2[key][-1])
print(properties2["left_ips"])
if properties2["left_ips"].size > 0:
p2[baboon] = math.floor(properties2["left_ips"]) + two_third
peak1.append(p1)
peak2.append(p2)
# In[16]:
#Visualize distances
from plotly.subplots import make_subplots
import plotly.graph_objects as go
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing = 0.2)
for day in range(len(tms_days)):
# print(day)
for baboon in interpolated_x_days[day].columns:
if baboon != 'centroid1' and day >= second_last_day_available[baboon]:
continue
if baboon != 'centroid1':
fig.add_trace(go.Scatter(name = f'D{day}.{baboon}', x=distances1[day][baboon]['time'], y=distances1[day][baboon]['distance'],
mode='lines'),
row=1, col=1)
if baboon == 'centroid1':
fig.add_trace(go.Scatter(name = f'D{day}.{baboon}', x=distances1[day][baboon]['time'], y=distances1[day][baboon]['distance'],
mode='lines',
marker = {'color' : 'black'}),
row=1, col=1)
fig.add_shape(name = 'Peak1', type="line",
x0=distances1[day][baboon].loc[peak1[day]['centroid1'], 'time'], y0=0, x1=distances1[day][baboon].loc[peak1[day]['centroid1'], 'time'], y1=700,
line=dict(
color="purple",
width=1,
dash="dot",
),
row=1, col=1
)
fig.add_shape(name = 'Peak2', type="line",
x0=distances1[day][baboon].loc[peak2[day]['centroid1'], 'time'], y0=0, x1=distances1[day][baboon].loc[peak2[day]['centroid1'], 'time'], y1=700,
line=dict(
color="purple",
width=1,
dash="dot",
),
row=1, col=1
)
for day in range(len(tms_days)):
for baboon in interpolated_x_days[day].columns:
if baboon != 'centroid1' and day >= second_last_day_available[baboon]:
continue
fig.add_trace(go.Scatter(name = f'D{day}.{baboon}',x=distances_from_start1[day][baboon]['time'], y=distances_from_start1[day][baboon]['distance'],
mode='lines'),
row=2, col=1)
if baboon == 'centroid1':
fig.add_trace(go.Scatter(name = f'D_start{day}_{baboon}', x=distances_from_start1[day][baboon]['time'], y=distances_from_start1[day][baboon]['distance'],
mode='lines',
marker = {'color' : 'black'}),
row=2, col=1)
fig.add_shape(name = 'Peak1', type="line",
x0=distances1[day][baboon].loc[peak1[day]['centroid1'], 'time'], y0=0, x1=distances1[day][baboon].loc[peak1[day]['centroid1'], 'time'], y1=2100,
line=dict(
color="purple",
width=1,
dash="dot",
),
row=2, col=1
)
fig.add_shape(name = 'Peak2', type="line",
x0=distances1[day][baboon].loc[peak2[day]['centroid1'], 'time'], y0=0, x1=distances1[day][baboon].loc[peak2[day]['centroid1'], 'time'], y1=2100,
line=dict(
color="purple",
width=1,
dash="dot",
),
row=2, col=1
)
fig.update_xaxes(title='Time', showticklabels=True, row=1, col=1)
fig.update_xaxes(title='Time', row=2, col=1)
fig.update_yaxes(title='Distance', row=2, col=1)
fig.update_yaxes(title='Distance', row=1, col=1)
fig.show()
# In[ ]:
#This takes about an hour to run
import datetime
#duration: return - start (in hours)
#reverse: The naming suggests the time of direction reversal, but it is misleading. This variable stores the time when the
#baboons stop moving farther from where they would return.
#max_dists: The maximum distance they would travel on the way back. Identify the time when they were farthest from the return
#site, and find the distance they travelled from that time until they reached (using distances_from_return_new)
#avg_speed: Average speed after return initiation upto the end of journey
#max_speed: Maximum speed after return initiation
#dist: Distance from return site at the time of return initiation
to_plot = pd.DataFrame(columns = ['day', 'site', 'durations', 'starts', 'reverse', 'max_dists', 'returns', 'avg_speed', 'max_speed', 'dist'])
to_plot_c = pd.DataFrame(columns = ['day', 'site', 'durations', 'starts', 'reverse', 'max_dists', 'returns', 'avg_speed', 'max_speed', 'dist'])
#the following two are for the line plots of distances from return site after return initiation
time_vs_dist = pd.DataFrame(columns = ['day', 'site', 'baboon', 'return_time', 'distance', 'speed'])
time_vs_dist_c = pd.DataFrame(columns = ['day', 'site', 'baboon', 'return_time', 'distance', 'speed'])
baboons_variations_return = dict.fromkeys(list(interpolated_x_days[0].columns))
for b in baboons_variations_return.keys():
baboons_variations_return[b] = pd.DataFrame(columns = ['day', 'difference'])
durations = []
other_durations = []
max_dists = []
starts = []
returns = []
return_inits = []
rmax_dist = []
centroid_starts = []
centroid_returns = []
centroid_dur = []
other_centroid_dur = []
centroid_maxdist = []
centroid_return_inits = []
centroid_rmax_dist = []
avg_speed = []
max_speed = []
centroid_avg_speed = []
centroid_max_speed = []
times_to_plot = pd.DataFrame()
i = 0
j = 0
days = [0, 4, 5, 6, 7, 8, 9, 10, 13, 16]
A = [3, 8, 23, 27]
A_ = [16, 17, 19]
B = [0, 1, 6, 14]
C = [9, 10, 13, 24, 26, 28, 30, 32]
D = [4, 15, 18, 25, 33]
E = [2, 5, 7, 11, 12, 15, 29, 31]
L = [20, 21, 22]
day_site_dict = {}
for day in range(len(tms_days)):
if day in A:
day_site_dict[day] = 'A'
elif day in A_:
day_site_dict[day] = 'A_'
elif day in B:
day_site_dict[day] = 'B'
elif day in C:
day_site_dict[day] = 'C'
elif day in D:
day_site_dict[day] = 'D'
elif day in E:
day_site_dict[day] = 'E'
else:
day_site_dict[day] = 'L'
centroid_ret = []
ct = 0
r1 = 0
r2 = 0
for day in range(30):
print(day)
k = 0
for baboon in interpolated_x_days[day].columns:
if baboon != 'centroid1' and day >= second_last_day_available[baboon] - 1:
continue
if baboon != 'centroid1' and len(distances_from_return1[day][baboon]) > 0:
try:
distances_from_return_new1[day][baboon] = distances_from_return_new1[day][baboon].sort_values(by = ['time']).reset_index(drop = True)
# first = end_of_beg[day][baboon]
this_baboon = baboons_variations_return[baboon]
k = len(this_baboon)
first = peak1[day][baboon]
last = peak2[day][baboon]
firstc = peak1[day]['centroid1']
lastc = peak2[day]['centroid1']
this_baboon.loc[k, 'day'] = day + 1
this_baboon.loc[k, 'difference'] = ((distances_from_return_new1[day][baboon].loc[last, 'time']).hour + (distances_from_return_new1[day][baboon].loc[last, 'time']).minute /60 + (distances_from_return_new1[day][baboon].loc[last, 'time']).second /3600) - ((distances_from_return_new1[day]['centroid1'].loc[lastc, 'time']).hour + (distances_from_return_new1[day]['centroid1'].loc[lastc, 'time']).minute /60 + (distances_from_return_new1[day]['centroid1'].loc[lastc, 'time']).second /3600)
if (distances_from_return1[day][baboon].loc[last, 'time']).hour > 10:
r = last
while r <= max(distances1[day][baboon].index):
# print(day)
time_vs_dist.loc[r1, 'return_time'] = (distances_from_return_new1[day][baboon].loc[r, 'time']).hour + (distances_from_return_new1[day][baboon].loc[r, 'time']).minute /60 + (distances_from_return_new1[day][baboon].loc[r, 'time']).second /3600
time_vs_dist.loc[r1, 'distance'] = distances_from_return_new1[day][baboon].loc[r, 'distance']
time_vs_dist.loc[r1, 'speed'] = distances1[day][baboon].loc[r, 'distance']/5
time_vs_dist.loc[r1, 'day'] = day
time_vs_dist.loc[r1, 'baboon'] = baboon
time_vs_dist.loc[r1, 'site'] = day_site_dict[day]
r+= 1
r1+= 1
starts.append(datetime.datetime.time(distances_from_return_new1[day][baboon].loc[first, 'time']))#.hour + (distances_from_return[day][baboon].loc[first, 'time']).minute * 0.01)
# last = max(distances_from_return[day][baboon]['time'].index)
ct += 1
# last = max_neg[day][baboon]
if day in A:
to_plot.loc[i, 'site'] = 'A'
elif day in A_:
to_plot.loc[i, 'site'] = 'A_'
elif day in B:
to_plot.loc[i, 'site'] = 'B'
elif day in C:
to_plot.loc[i, 'site'] = 'C'
elif day in D:
to_plot.loc[i, 'site'] = 'D'
elif day in E:
to_plot.loc[i, 'site'] = 'E'
else:
to_plot.loc[i, 'site'] = 'L'
to_plot.loc[i, 'day'] = day
to_plot.loc[i, 'starts'] = (distances_from_return_new1[day][baboon].loc[first, 'time']).hour + (distances_from_return_new1[day][baboon].loc[first, 'time']).minute /60 + (distances_from_return_new1[day][baboon].loc[first, 'time']).second /3600
to_plot.loc[i, 'returns'] = (distances_from_return_new1[day][baboon].loc[last, 'time']).hour + (distances_from_return_new1[day][baboon].loc[last, 'time']).minute /60 + (distances_from_return_new1[day][baboon].loc[last, 'time']).second /3600
to_plot.loc[i, 'durations'] = (distances_from_return_new1[day][baboon].loc[last, 'time'] - distances_from_return_new1[day][baboon].loc[first, 'time']).total_seconds()/3600
to_plot.loc[i, 'avg_speed'] = distances1[day][baboon].loc[last:max(distances1[day][baboon].index)]['distance'].mean(axis = 0)/300
to_plot.loc[i, 'max_speed'] = max(distances1[day][baboon].loc[last:max(distances1[day][baboon].index)]['distance'])/300
to_plot.loc[i, 'dist'] = distances_from_return_new1[day][baboon].loc[last, 'distance']
to_plot.loc[i, 'max_dists'] = distances_from_return_new1[day][baboon].loc[pd.to_numeric(distances_from_return1[day][baboon]['distance']).idxmax(), 'distance']
# to_plot.loc[i, 'max_dists'] = max(distances_from_return_new[day][baboon]['distance'])
change = list(distances_from_start1[day][baboon][distances_from_start1[day][baboon]['distance'] == max(distances_from_start1[day][baboon]['distance'])]['time'])[0]
to_plot.loc[i, 'reverse'] = change.hour + change.minute/60 + change.second/3600
i += 1