-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathForagingStateAnalysis.Rmd
More file actions
5409 lines (4150 loc) · 297 KB
/
ForagingStateAnalysis.Rmd
File metadata and controls
5409 lines (4150 loc) · 297 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
---
title: 'Notebook: Identifying the role of experience on foraging and exploration movement patterns'
output:
html_document:
df_print: paged
params:
output_dir: "/media/kostasl/D445GB_ext4/kostasl/Dropbox/Calculations/zebrafishtrackerData/foragingAnalysis"
html_notebook: default
pdf_document: default
bibliography: ForagingStateAnalysis.bib
---
The exploration patterns of zebrafish larvae are so far considered fixed having a robust statistical structure which can nevertheless be modulated by temperature - resulting in a thermophobic behavior - mainly via changing the sampling statistics of the distribution. This is also shown to be modulated by time (1h later traj. becomes longer-range which could be a result of hunger)
>We show that, for this simple animal model, five short-term kinematic parameters — interbout interval, turn amplitude, travelled distance, turn probability, and orientational flipping rate — (suffice) together control the long-term exploratory dynamics. We establish that the bath temperature consistently impacts the means of these parameters, but leave their pairwise covariance unchanged. These results indicate that the temperature merely controls the sampling statistics within a well-defined kinematic space delineated by this robust statistical structure.
([@goc2021thermal])
>These parameters however vary significantly over long time scales:
their time modulation takes place over hundreds to thousands of bouts, indicative of a clear time-separation between the two different processes. ([@goc2021thermal])
However, exploration and food search strategies should be suited to the and informaed by the structure of the environment:
>For a forager searching for prey in a stable, unchanging environment, prior expectation of when and where to find items will inform a deterministic search pattern (Stephens & Krebs 1986; Houston & McNamara 1999)
However, foragers in environments that couple complex prey distributions with stochastic dynamics will not be able to attain a universal knowledge of prey availability. This raises the question of how should a forager best search across complex landscapes to optimize the probability of encountering suitable
prey densities?
The contribution of learning by experience, may still be crucial in improving the relevance of the search patterns even in fluctuating environments, as experience can embed expectations by shaping the search patterns in relation to prey abundance.
My current aim to extend my previous work on the experience driven ontogeny of hunting skill [now published in eLife](https://elifesciences.org/articles/55119/figures) to examine the effect of experience on foraging motion.
This notebook, initially aimed at analysing zebrafish tracking data for foraging state as indicated by Marquez et al 2019.
According to Marquez et al 2020, Zebrafish appear to spontaneously switch between an exploratory and exploitation phase that grossly defines their behavioural mode.
The state can be read out be measuring trajectory dispersal over a fixed period of time (5 sec),
Measures of dispersal should appear bimodal, with short dispersals indicating exploitation phase.
Given our behavioural recordings are not continuous, and exclude periods when the larva are swimming around the boundary, it is not certain whether we would be able to detect exploratory phases. These tend to be circling around the border of the petri-dish, as the fish attempts to swim forward. Nevertheless as we are interested in the mode-state under which hunt-events are executed, then we expect that some of these events should be executed during exploratory behaviour and this should be detectable - (dispersal, movement rates etc).
In essense the internal state and the its neural correlates as reported by Marquez et al 2019 can combined with my results on the learned aspects of efficient hunting to study if this foraging state swithcing is also influenced by experience and whether differences in hunting kinematics correlate with internal state.
Hypothesis being tested :
- Does experience modify the dispersal and so the exploit/explore state of each group?
- Are foraging intervals modified based on priors built by experience and can these be modelled based on active inference ?(co-op with Rosalyn & Berk)
- Could expansion of foraging interval explain the higher evoked hunt-rate of the LF group?
- Does the execution of the kinematic adaptations of capture efficiency, found in the experience larvae, depend on foraging state ?
Establishing a correlation of hunting state with the kinematics of efficient hunting can point us to the underlying circuits, because the circuits that correlate with foraging state, but also with capture-success, have already been examined by Marquez et al 2019. So it would be posssible to use those to guide our search for the circuits that bring about the kinematics adaptations of success.
In a new twist of this work *I discover structure in the larval trajectories that indicates a random search process*.
Indeed although at the micro-scale larval do not move randomly, but have a rythm, it may well be the case (E.Raposo et al. 2009 ):
>Therefore, the foraging dynamics that defines the final outcomes of biological encounters becomes in essence a stochastic process (e.g. searches in landscapes
with low density of food sites).
The *Levy foraging hypothesis* predicts a Levy distribution of move-steps during foraging when prey is scarce, but an exponential distribution when prey is abundant and searching is not required.
Lévy flight increases the probability of encountering new patches (Viswanathan et al . 2000, 2002; Bartumeus et al . 2002). Lévy search strategies are also robust to changes in environmental parameters such as the availability of patchy resources (Raposo et al . 2003; Santos et al . 2004)
PhysOfForage: What is most important is that, over the course of two decades of study, a growing consensus among researchers in the relevant fields holds the view *that many organisms diffuse anomalously*: real organisms rarely have Gaussian probability functions for displacements with a variance that grows linearly in time. Rather, the motion of organisms is rich in variety and surprisingly complex.
In the absence of prey, the environment signals that prey is scarce, and in such conditions the optimal search strategy would be a Levy walk instead of brownian ([@viswanathan1999optimizing]).
*My recordings allow for the examination on whether search strategies are modified in the presence and absence of prey, and how experience of prey may modify these behaviours.*
I find that prey scarcity can modify larval general motion patterns in an adaptive manner such that larger areas are searched, yet prior experience of prey can strongly affect this behaviour.
The concept of a characteristic scale is used extensively in statistical physics for describing macroscopic behavior of physical systems.
In Levy walks/flights the step lengths (ie straight path lengths) are said tp have no characteristic scale, because they are power-law distributed.
In ([@humphries2010environmental]) it shown that searching animals adaptivelly adjust their optimal patterns of movement to different environmental resource distributions.
It remains unknown, however, whether the motions patterns arose as due to adaptive behaviour or whether observed patterns were an emergent property of the spatial distribution of prey (#sims2008scaling)
>What is the most efficient strategy to adopt while searching for randomly placed sites whose
locations are not apriori known for situations when the searcher has information only about
its close vicinity? (see E P Raposo et al 2009)
- Are these larvae executing Levy walks?
>From an evolutionary perspective, it is certainly pertinent to ask if efficient encounter rates are driven from selective pressures that systematically force organism adaption toward some optimal (or sub-optimal) solution.
However ([@reynolds2018passive]) shows that Levy like walks can arise simply through flowing in a turbulent environemnt and he generally argues that as movement patterns they can be easy and ubiquitous to obtain, and argues that that these are not about evolving optiml searches ([@reynolds2015liberating]).
#dunn2016brain discover rhombomere oscillator and suggests that spatiotemporal pattern of spontaneous swimming may improve exploration efficiency. They used markov model to show that L-R scheme covers a restricted area more efficiently than a model fish turning left and right randomly without turn history dependence, and reduces diffusion into faraway regions.
They argue _ that staying local is good foraging strategy:_
> the search for food cues represents an energetically favorable program that ensures no nearby resources have been missed.
Here use prior prey experience can alter the foraging search patterns in the scarcity and abundance of prey, to test wether changes in search patterns can be are adaptive, and not simply a result of interacting with dense prey environments. Thus if prior expectations on abandunce of prey can modify motion, then changes in search patterns can be shown to be adaptive.
Thus we explore whether animals evolved to exploit experience in their search patterns, and whether they can use optimal search strategies such as Levy flights/walks when prey is scarce.
I need to understand what changes in these walks, in terms of step length -
Generally the LF group shows a bimodal distribution of path length and an increase in the overall path length. which could be indicative of increased number of re-orientations. There is also a decrease in path-length between spontaneous and evoked conditions (most evident in LF )
*Main Findings so far :*
1. LF larvae are quicker to disperse (as seen in 20 sec path duration) and larval normalized dispersion (see Marquez et al. 2019)
2. Path lengths over 5sec are bimodal, like dispersions; clearly for LF. LF show longer pathlengths in 5sec to controls in both conditions (Low occupancy in small path mode).
3. Bimodal path length distribution in Evoked is modified towards longer paths and closing of bimodal gap, and extending path range
4. Evoked Hunt events occur over the shorter movement sub-range/mode of the overall distribution
5. Path lengths are longer in Evoked for the same dispersion size , more clearly so for LF (see also pathL/Dispersion Ratio).
6. Invariance of Mean-Path Length when crossing bounded domain r -across groups- is evidence of stochastic process.
7. Mean *residence time* within domain clearly Shorter for LF, and most for LE.
7.1 Duration of paths crossing domain have *fat tails except for LE*, suggesting experience increases tendency to search for new patches and not dwell on same spot.
8. Path length distributions drop as power-law like after $l> 2 \times r$ (check exponent).
9. Distribution Of Path Length Shows Power law drop-off for lengths exceeding the $2*r$ of the domain (chord distrib. seen in [ref].)
10. With increasing domain $r$, Spontaneous conditions (all groups), but also LL, show *scale-invariance in the fraction of boundary crossings* against $r$, *but NL,DL prefers <6mm domains* thus confined to search smaller areas.
for other patches.
11. *LF disperse faster* than controls, with *LE dispersing the fastest*.
12. *LF move faster*, making longer path lengths over time but also leavin the ROI earlier;
13. There are almost no paths with more than 40sec duration in LE, but this increases to 130sec for LL. *Probability of path duration clearly drops faster for increasing duration for LE*, than controls (We also have path durations within Domain R=10mm duration distributions showing less than 50sec)
14. MSD over path duration clearly higher for LE, with max overshooting within 10sec,rather than 100 as in controls.
15. Evidence of super-diffusion as MSD grows supra linearly to path-length (Within some range < 21mm), *MSD growth distinct for LE*
16. MSD vs Dispersion are linearly related, with a drop-off in Evoked conditions over large dispersion.
17. -Clustering And Bimodality results-.
18. Spontaneous Hunt events associated with higher dispersions than Evoked, only for LF. NF, look the same, DF, do the opposite to LF.
19. Hunt-outcome is not associated to Dispersion, but only in LL do all successful events belong to fast-cluster
20. Hunting probability is higher in the large dispersion cluster for all groups.
21. **Bout Structure**:
- LF has Lower number of bouts per free-path
- LF has Longer distance traveled per bout - *longer bouts*
- Bout duration and distances decrease for LF,NF in evoked conditions, but not for DF.
- Lower number of bouts between turns (maybe).
- Inter-Bout intervals *show fat-tails for DF and NF* LF does not do long-pause/ Waits, in contrast to DF, NF.
- Lower mean number of turns when crossing Domain 10mm for DE, and then LL,DL, and then LE- NE has highest
- Increasing turn Modes around 40-50 deg, in spontaneous conditions, across groups. (Surprise as these turn modes are associated with Successful hunts)
- *Bout Speed increases in absence of prey*, with LF having the fastest bouts on average and DF the slowest.
22. _Prey Density Effect on Dispersion And MSD_ :
# Analysis of larval trajectories
## Examine dispersion to reveal foraging state as in Marquez et al. 2019
5s window measure radius encompassing trajectory
```{r setup, message=FALSE, cache=FALSE, results='hide', echo=FALSE, warning=FALSE}
## Init Code
library(rjags)
library(runjags)
library('coda')
### library(targets) To convert project into Pipeline
message("Jags version: ",jags.version())
message(" For info in runjags check out:doi: 10.18637/jss.v071.i09")
setwd("/home/kostasl/workspace/zebrafishtrack/Rplots") ##sOME bUG REQUIRES THAT THIS IS RUN ON CONSOLE MANUALLY
#setwd(here())
source("config_lib.R")
source("TrajectoryAnalysis.r")
source("HuntingEventAnalysis_lib.r")
setEnvFileLocations("HOME") #HOME,OFFICE,#LAPTOP
## To compile to different destination run:
# rmarkdown::render("ForagingStateAnalysis.Rmd",output_dir = paste0(strDataExportDir,'../foragingAnalysis') )
MIN_PATH_LENGTH <- 0.5
tsec_timeWindow <- 5
thres_dispersion_class <- 0.2
##Clustering
Nclust <- 2
nsubsampleInterval <- G_APPROXFPS/2
vGroups <- c("LL","LE","NL","NE","DL","DE")
## Load datAllFrames
loaddatAllFrames <- function(forceReload = FALSE)
{
if (!exists("datAllFrames") | forceReload)
{
attach(paste(strDatDir,"datAllFramesFix1_Ds-5-19.RData",sep="/"))
attach(paste(strDatDir,"groupsrcdatListPerDataSet_Ds-5-19.RData",sep="/"))
}
}
#Original Dispersion Record per frame
#datDispersion = readRDS(file=paste0(strDataExportDir,"/foragingState_Dispersion",tsec_timeWindow,"sec.rds") )
## Extended Dispersion Merged With maxDispersion Data
# Param tsec_timeWindow=0 default value loads pathstat calculated over the full event length - Not Confined to moving Time Window of X sec
loadDispersionData <- function(forceReload = FALSE, tsec_timeWindow=0)
{
if (exists("Interval")){
if (datDispersion.Interval != tsec_timeWindow)
forceReload <- TRUE
}
try(
##Check If Already Loaded
if (!exists("datDispersion") | forceReload)
{
strFile <- paste0(strDataStore,"/foragingState_Dispersion",tsec_timeWindow,"sec.rds")
message(strFile)
datDispersion <<- readRDS(file=strFile )
}
)
if (!exists("datDispersion"))
{
message("Calculate Trajectory Dispersions")
loaddatAllFrames()
datDispersion <<- calcTrajectoryDispersions(datAllFrames,tsec_timeWindow)
}
AllRange <<- range(datDispersion$Dispersion,na.rm=TRUE)
##Change Global Ref to Last Call
datDispersion.Interval <<- tsec_timeWindow
##tsec_timeWindow <<- tsec_timeWindow
return(datDispersion)
}
## PathStat Data Merged onto Hunt Event based on initiation frame
loadHuntEventMergedWithPathStat <- function(tsec_timeWindow)
{
datHEventDispersion <- data.frame()
strFile <- paste0(strDataStore,"/huntEvent_mergedwith_Dispersion",tsec_timeWindow,"sec.rds")
if (file.exists(strFile))
{
message("Loading from :",strFile )
try(
datHEventDispersion <- readRDS(file=strFile )
)
}else
{
message("Merged Data not generated yet ",strFile )
}
## If we have not merged these records before, make them now
if (!exists("datHEventDispersion") | !file.exists(strFile))
{
loaddatAllFrames()
datDispersion <- loadDispersionData_norm(tsec_timeWindow)
datHuntLabelledEventsSBMerged_fixed <- getLabelledHuntEventsSet() # readRDS(file=paste(strDatDir,"/LabelledSet/",strProcDataFileName,".rds",sep="" ))
datHEventDispersion <- mergeDispersionOntoHuntEvents(datDispersion,datAllFrames,datHuntLabelledEventsSBMerged_fixed)
}
return(datHEventDispersion)
}
## Check list of foragingStateDispersion files and return vector with the processed and available path-dispersion-msd Analysis timewindows
getAvailablePathTimewindows <- function()
{
# Check List of Available Calculated PathMeasure files (Dispersion etc)
# helper function : Convert WildCard to RegExp : glob2rx("foragingState_Dispersion???sec.rds", trim.head = FALSE, trim.tail = TRUE)
lAvailableDispersionFiles <- dir(strDataStore, pattern = "foragingState_Dispersion[0-9]{1,3}sec.rds", full.names = FALSE, ignore.case = TRUE)
vAvailabletimeWindows <- lapply( lAvailableDispersionFiles,FUN = function(s){ gsub(pattern = "[^0-9]", replacement = "", x = s) } )
#Order them and Converr to Number
vtimeWindows <- as.integer(unlist(vAvailabletimeWindows[order(as.integer(unlist(vAvailabletimeWindows)))] ) )
message("Available timewindows:",paste(vAvailabletimeWindows,collapse=","))
return (vtimeWindows)
}
getAvailablePathDomainsSizes <- function()
{
#lBoundedTrajectoryFiles <- dir(strDataExportDir, pattern = "stat_boundedPathsB_R[0-9]{1,3}mm.rds", full.names = FALSE, ignore.case = TRUE)
lBoundedTrajectoryFiles <- dir(strDataExportDir, pattern = "stat_boundedPathsB_R[[:digit:]]+\\.*[[:digit:]]*mm.rds", full.names = FALSE, ignore.case = TRUE)
vAvailableDomainRadius <- lapply( lBoundedTrajectoryFiles,FUN = function(s){ gsub(pattern = ".rds", replacement = "", x = s) } )
vAvailableDomainRadius <- lapply( vAvailableDomainRadius,FUN = function(s){ gsub(pattern = "[^0-9,.]", replacement = "", x = s) } )
vAvailableDomainRadius <- as.numeric(unlist(vAvailableDomainRadius[order(as.numeric(unlist(vAvailableDomainRadius)))] ) )
return(vAvailableDomainRadius)
}
##Re Run All Path Calculation
generate_DispersionFiles <- function()
{
##Generate Files From Start
loaddatAllFrames()
for (tt in seq(2,6,2) )
calcTrajectoryDispersions(datAllFrames,tsec_timeWindow)
}
## iNvariance Principle Theoretical Mean Path Length
theoreticalMeanLength <- function(D,propFactor=1.0)
{
A <- pi*( (D)^2)
C <- 2*pi*(D)
return(round(100*(propFactor* pi*A/C)) /100 )
}
```
```{r merge max larval-dispersion onto dispersion data events, echo=FALSE,cache=FALSE,results=FALSE,warning=FALSE}
## Attaches the max Dispersion found between both evoked and spontaneous trajectories of each larva
## This is used so we can combine S/E larval recordings to detect both exploration/ exploitation state - and normalize appropriatelly to the joined trajectrories between tests as if they were ## one 20min recording
mergeRangeOfLarvalDispersionPerLarvaOntoDispersion <- function(datDispersion,datExpPairs,tsec_timeWindow)
{
## Merge Max Dispersion per larva Onto Dispersion data (so we can normalize on a per larva basis instead of experiment basis)
## Calc Normalization to Max Dispersion by combining both Spont And Exoked cond per larva
## Find Max Dispersion Per Experiement
datDispersionMax <- data.frame(tapply(datDispersion$Dispersion,datDispersion$expID,max,na.rm = TRUE))
datDispersionMin <- data.frame(tapply(datDispersion$Dispersion,datDispersion$expID,min,na.rm = TRUE))
## pair each experiemnt with its max dispersion between Spontaneous and Evoked conditions of a larva
## We use this struct to merge with Dispersion data of each frame / So as to normalize approprietelly
datDispesionRange_Pairs <- rbind.data.frame(
cbind.data.frame(
expID = as.character(datExpPairs$expID.S) ,
groupID = as.character(datExpPairs$groupID.S),
max_exp_Disp = datDispersionMax[as.character(datExpPairs$expID.S),],
max_exp_Disp.C = datDispersionMax[as.character(datExpPairs$expID.E),],
min_exp_Disp = datDispersionMin[as.character(datExpPairs$expID.S),],
min_exp_Disp.C = datDispersionMin[as.character(datExpPairs$expID.E),]),
cbind.data.frame(
expID = as.character(datExpPairs$expID.E) ,
groupID = as.character(datExpPairs$groupID.E),
max_exp_Disp = datDispersionMax[as.character(datExpPairs$expID.E),],
max_exp_Disp.C = datDispersionMax[as.character(datExpPairs$expID.S),],
min_exp_Disp = datDispersionMin[as.character(datExpPairs$expID.E),],
min_exp_Disp.C = datDispersionMin[as.character(datExpPairs$expID.S),])
)
## Add col for Max/min Dispersion across Spont and Evoked conditions
datDispesionRange_Pairs$max <- as.numeric(apply(datDispesionRange_Pairs[,3:4], 1, max,na.rm=TRUE))
datDispesionRange_Pairs$min <- as.numeric(apply(datDispesionRange_Pairs[,5:6], 1, min,na.rm=TRUE))
##Make Simple frame for merging with dispersion data
datMaxDispersionPerLarva <- cbind.data.frame(expID=as.character(datDispesionRange_Pairs$expID),
groupID=as.character(datDispesionRange_Pairs$groupID),
max_larval_Dispersion=(datDispesionRange_Pairs$max),
min_larval_Dispersion=(datDispesionRange_Pairs$min),
max_exp_Dispersion=(datDispesionRange_Pairs$max_exp_Disp), # Add The max Disp Recorded for this larva
min_exp_Dispersion=(datDispesionRange_Pairs$min_exp_Disp) # Add The max Disp Recorded for this larva
)
datDispersionM <- merge(datDispersion,datMaxDispersionPerLarva,all.x = TRUE,by=c("expID","groupID"),no.dups=FALSE)
#Calculate Range Normalized dispersion per larva - to match Marquez et al 2019
## Save dispersion data normalized across Spont and evoked condition for each larva (saves time in future plotting)
datDispersionM <- cbind.data.frame(datDispersionM,
Dispersion_larval_norm=(datDispersionM$Dispersion-datDispersionM$min_larval_Dispersion) / (datDispersionM$max_larval_Dispersion-datDispersionM$min_larval_Dispersion) )
## Now Merge onto Dispersion Data
saveRDS(datDispersionM,file=paste0(strDataExportDir,"/foragingState_Dispersion_merged_rangeperLarva_",tsec_timeWindow,"sec.rds") )
saveRDS(datMaxDispersionPerLarva,file=paste0(strDataExportDir,"/foragingState_max_Dispersion_perLarva_",tsec_timeWindow,"sec.rds") )
message("Saved to:",paste0(strDataExportDir,"/foragingState_Dispersion_merged_rangeperLarva_",tsec_timeWindow,"sec.rds") )
message("Saved to:",paste0(strDataExportDir,"/foragingState_max_Dispersion_perLarva_",tsec_timeWindow,"sec.rds") )
return(datDispersionM)
}
```
```{r merge hunt-events with dispersion data, fig.show="hold", out.width="50%", echo=FALSE, cache=FALSE,results=FALSE,message=FALSE,warning=FALSE }
source("DataLabelling/labelHuntEvents_lib.r")
source("HuntingEventAnalysis_lib.r")
#loadDispersionData(forceReload = TRUE,tsec_timeWindow = 0)
##Load Dispersion Data, check if data.frame has been extended with larva ranges, and merge if need to have been added -
loadDispersionData_norm <- function(tsec_timeWindow,forceReload=TRUE)
{
if (exists("datDispersion.Interval"))
{
if (datDispersion.Interval != tsec_timeWindow)
{
forceReload <- TRUE
try(rm("datDispersion"),silent=TRUE);
}
}
strFile <- paste0(strDataStore,"foragingState_Dispersion_merged_rangeperLarva_",tsec_timeWindow,"sec.rds")
if (file.exists(strFile) & !exists("datDispersion") )
{
try( {
message("Loading ",strFile);
datDispersion <<- readRDS(file=strFile ) ;
}
)
}
if (exists("datDispersion") )
message("Dispersion data already loaded.")
if (!file.exists(strFile))
message("No Dispersion data file found: ", strFile,"\n Attempting to generate now ...")
##If the Merged Version is not found then GENERATE IT
if (!exists("datDispersion") | !file.exists(strFile))
{
datDispersion <- loadDispersionData(forceReload = forceReload, tsec_timeWindow)
datDispersion.Interval <<- tsec_timeWindow
}
## Merge Max Dispersion on there - If it is not already there then Calculate and save
if (!any(grepl("max_larval_Dispersion",names(datDispersion)) ) |
!any(grepl("min_larval_Dispersion",names(datDispersion)) ) |
!any(grepl("Dispersion_larval_norm", names(datDispersion)) ) )
datDispersion <<- mergeRangeOfLarvalDispersionPerLarvaOntoDispersion(datDispersion,datExpPairs,tsec_timeWindow)
return(datDispersion)
}
#load(file=paste(strDatDir,"/LabelledSet/",strProcDataFileName,".RData",sep="" )) ##Save With Dataset Idx Identifier
datHuntLabelledEventsSBMerged_fixed <- getLabelledHuntEventsSet() # readRDS(file=paste(strDatDir,"/LabelledSet/",strProcDataFileName,".rds",sep="" ))
##Clear Warningss : assign("last.warning", NULL, envir = baseenv()
## Link Evoked and Spontaneous Trajectories
datHuntStat <- makeHuntStat(datHuntLabelledEventsSBMerged_fixed)
datExpPairs <- getSpontaneousEvokedExperimentPairs(datHuntStat)
datHEventDispersion <<- loadHuntEventMergedWithPathStat(5)
loadDispersionData_norm(tsec_timeWindow)
## Check for max Calc Error
#datDispersion[datDispersion$Dispersion > datDispersion$max_Dispersion,]
```
```{r plot-trajectories-figures-function, fig.show="hold", out.width="50%", echo=FALSE ,results=FALSE,ref.label='setup',warning=FALSE}
#Function to plot trajectories for each larva coloured based on dispersion
pairedTrajPalette <- col2hex(col2rgb(brewer.pal(12,"Paired"),alpha = 1))
#
# Function Plot Individual Trajectories for a group, split between exploration and exploitation
# given a *global* normalized dispersion measures threshold
#
plotGlobalNormDispersionTrajectories <- function(groupID, datAllFrames, datDispersion, datHEventDispersion,datExpPairs,TH_DISP = 0.2)
{
datGroupExploreTraj <- datAllFrames[datDispersion[datDispersion$groupID %in% groupID & datDispersion$Dispersion/AllRange[2] >= TH_DISP,"frameRow"],]
datGroupExploitTraj <- datAllFrames[datDispersion[datDispersion$groupID %in% groupID & datDispersion$Dispersion/AllRange[2] < TH_DISP ,"frameRow"],]
## ind Exploration Hunt Events
datExplorationHuntEvents <- datHEventDispersion[datHEventDispersion$Dispersion/AllRange[2] >= TH_DISP, ]
## ind Exploration Hunt Events
datExploitationHuntEvents <- datHEventDispersion[datHEventDispersion$Dispersion/AllRange[2] < TH_DISP, ]
plotExploreExploitTrajectories(groupID,datGroupExploreTraj,datGroupExploitTraj, datExplorationHuntEvents,
datExploitationHuntEvents,datDispersion,
datExpPairs[datExpPairs$groupID.E %in% groupID | datExpPairs$groupID.S %in% groupID, ]) ##Subset to Targeted groups
} ## end of plot Function
##
# Function Plot Individual Trajectories for a group, split between exploration and exploitation
# given a *local* normalized dispersion measures threshold / the classification is relative to the mobility measure of each larvae in each condition
##
plotExpNormDispersionTrajectories <- function(groupID, datAllFrames, datDispersion,datHEventDispersion, datExpPairs,TH_DISP = 0.2)
{
datGroupExploreTraj <- datAllFrames[datDispersion[datDispersion$groupID %in% groupID & datDispersion$Dispersion_norm >= TH_DISP,"frameRow"],]
datGroupExploitTraj <- datAllFrames[datDispersion[datDispersion$groupID %in% groupID & datDispersion$Dispersion_norm < TH_DISP,"frameRow"],]
## \TODO: Norm per larva in both spont and Evoked
## ind Exploration Hunt Events
datExplorationHuntEvents <- datHEventDispersion[datHEventDispersion$Dispersion_norm >= TH_DISP, ]
## ind Exploration Hunt Events
datExploitationHuntEvents <- datHEventDispersion[datHEventDispersion$Dispersion_norm < TH_DISP, ]
## Call Plot Function - Both Spont And Evoked plo tted on same figure
plotExploreExploitTrajectories(groupID,datGroupExploreTraj,datGroupExploitTraj, datExplorationHuntEvents,
datExploitationHuntEvents,datDispersion,
datExpPairs[datExpPairs$groupID.E %in% groupID | datExpPairs$groupID.S %in% groupID, ]) ##Subset to Targeted groups
} ## end of plot Functon
## TODO: plot NB Mix clustered traj
# Function Plot Individual Trajectories for a group, split between exploration and exploitation
# given based on threshold placed on the normalized dispersion of the trajectories from combined spont and evoked conditions of each larva .
##
plotNBMixGClusteredDispersionTrajectories <- function(groupID, datAllFrames, datDispersion, datHEventDispersion,datExpPairs,TH_DISP = 0.2)
{
#load(file=paste0(strDataExportDir,'jagsModelTestResults_NBMixGroupclustDispersion_All.RData') )
#datHEventDispersion <<- readRDS(file=paste0(strDataExportDir,"/huntEvent_mergedwith_Dispersion",tsec_timeWindow,"sec.rds") )
datHEventDispersion <<- loadHuntEventMergedWithPathStat(5)
## Merge sparse Clustered Dispersions Results onto full Dispersion Data
lparamsAll <- getMCMCNBGroupEstimatedParams(results.All,"All",2)
if (!("clustID" %in% names(datSubDispersion)))
datSubDispersion$clustID <- as.vector(lparamsAll$clustID)
##Add Clust ID on all Dispersion Data - interpolating the sparse datSubDispersion
datDispersion$clustID <- NA
datDispersion[datSubDispersion$frameRow,"clustID"] <- datSubDispersion$clustID
##Fill in the gaps with the last value
lastClustID <- NA
idxA <- 1:NROW(datDispersion)
for (i in 1:nsubsampleInterval )
{
datDispersion[idxA+i,"clustID"] <- datDispersion[idxA,"clustID"]
}
##Merge Cluster ID onto Hunt Events
datHEventDispersion <- merge(datHEventDispersion, cbind.data.frame (frameRow=datSubDispersion$frameRow,
#expID=datSubDispersion$expID,
#groupID=datSubDispersion$expID,
clustID=as.numeric(datSubDispersion$clustID) ),
by=c("frameRow"),all.x =TRUE,no.dups = FALSE)
datGroupExploreTraj <- datAllFrames[datDispersion[datSubDispersion$groupID %in% groupID & datDispersion$clustID == 1,"frameRow"],]
datGroupExploitTraj <- datAllFrames[datDispersion[datSubDispersion$groupID %in% groupID & datDispersion$clustID == 2,"frameRow"],]
## ind Exploration Hunt Events
datExplorationHuntEvents <- datHEventDispersion[datHEventDispersion$clustID == 1, ]
## ind Exploration Hunt Events
datExploitationHuntEvents <- datHEventDispersion[datHEventDispersion$clustID ==2, ]
plotExploreExploitTrajectories(groupID,datGroupExploreTraj,datGroupExploitTraj, datExplorationHuntEvents,
datExploitationHuntEvents,datDispersion,
datExpPairs[datExpPairs$groupID.E %in% groupID | datExpPairs$groupID.S %in% groupID, ],thin=5) ##Subset to Targeted groups
} ##
##
# Function Plot Individual Trajectories for a group, split between exploration and exploitation
# given based on threshold placed on the normalized dispersion of the trajectories from combined spont and evoked conditions of each larva .
##
plotLarvaNormDispersionTrajectories <- function(groupID, datAllFrames, datDispersion, datHEventDispersion,datExpPairs,TH_DISP = 0.2)
{
datGroupExploreTraj <- datAllFrames[datDispersion[datDispersion$groupID %in% groupID & datDispersion$Dispersion_larval_norm >= TH_DISP,"frameRow"],]
datGroupExploitTraj <- datAllFrames[datDispersion[datDispersion$groupID %in% groupID & datDispersion$Dispersion_larval_norm < TH_DISP,"frameRow"],]
## ind Exploration Hunt Events
datExplorationHuntEvents <- datHEventDispersion[datHEventDispersion$Dispersion_larval_norm >= TH_DISP, ]
## ind Exploration Hunt Events
datExploitationHuntEvents <- datHEventDispersion[datHEventDispersion$Dispersion_larval_norm < TH_DISP, ]
plotExploreExploitTrajectories(groupID,datGroupExploreTraj,datGroupExploitTraj, datExplorationHuntEvents,
datExploitationHuntEvents,datDispersion,
datExpPairs[datExpPairs$groupID.E %in% groupID | datExpPairs$groupID.S %in% groupID, ]) ##Subset to Targeted groups
} ##
## Plot function for scatter plot of colour coded larval trajectories, separated into explore and exploit vectors
## with Both Spont And Evoked plotted on same figure
### datExpPairs - expID for Spont and Evoked for each larva
plotExploreExploitTrajectories <- function(groupID,datGroupExploreTraj,datGroupExploitTraj, datExplorationHuntEvents, datExploitationHuntEvents, datDispersion, datExpPairs, thin=3,TH_DISP = 0.2)
{
#vexpID <- unique(datGroupExploitTraj$exp)
#par(mfrow=c(2,NROW(vexpID))) ##MultiPlot Page
#par(mar=c(1,1,1,1))
#layout(matrix(seq(1,NROW(vexpID)), 2,NROW(vexpID) , byrow = TRUE))
i <- 0
for (j in 1:nrow(datExpPairs) )
{
e <- datExpPairs[j,]
if (is.na(e$expID.E))
next()
x1 <- seq(0, 640 )
y1 <- seq(0, 550 )
#print(e)
plot(0,0,ylim=range(y1),xlim=range(x1), type="l", col="red", main=paste(groupID[1],e$expID.E,"/",groupID[2],e$expID.S) )
## Evoked Exploration
datTraj <- datGroupExploreTraj[datGroupExploreTraj$expID == as.character(e$expID.E) & !is.na(datGroupExploreTraj$posX),]
if (NROW(datTraj))
{
idxplot <- seq(1,NROW(datTraj),thin)
points(datTraj[idxplot,]$posX,datTraj[idxplot,]$posY,type="p", col=pairedTrajPalette[1], cex=0.1);
}
## Add Hunt Events on Map
# Evoked Exploration
datSpotHunts.E.Explore <- datExplorationHuntEvents[datExplorationHuntEvents$expID == as.character(e$expID.E) & !is.na(datExplorationHuntEvents$expID), ]
points(datSpotHunts.E.Explore$posX, datSpotHunts.E.Explore$posY, col=pairedTrajPalette[2], cex=1.2, pch=17) ## Triangle Explore
## Spontaneous Explore
datTraj <- datGroupExploreTraj[datGroupExploreTraj$expID == as.character(e$expID.S) & !is.na(datGroupExploreTraj$posX),]
if (NROW(datTraj))
{
idxplot <- seq(1,NROW(datTraj),thin)
points(datTraj[idxplot,]$posX,datTraj[idxplot,]$posY,type="p", col=pairedTrajPalette[3], cex=0.1);
}
## Spont Exploration
datSpotHunts.S.Explore <- datExplorationHuntEvents[datExplorationHuntEvents$expID == as.character(e$expID.S) & !is.na(datExplorationHuntEvents$expID), ]
points(datSpotHunts.S.Explore$posX, datSpotHunts.S.Explore$posY, col=pairedTrajPalette[4], cex=1.2, pch=17) ## Triangle Explore
## Evoked Exploit
datTraj <- datGroupExploitTraj[datGroupExploitTraj$expID == as.character(e$expID.E) & !is.na(datGroupExploitTraj$posX),]
if (NROW(datTraj))
{
idxplot <- seq(1,NROW(datTraj),thin)
points(datTraj[idxplot,]$posX,datTraj[idxplot,]$posY,type="p",col=pairedTrajPalette[5], cex=0.1)
}
## Evoked Exploitation
datSpotHunts.E.Exploit <- datExploitationHuntEvents[datExploitationHuntEvents$expID == as.character(e$expID.E) & !is.na(datExploitationHuntEvents$expID), ]
points(datSpotHunts.E.Exploit$posX, datSpotHunts.E.Exploit$posY,col=pairedTrajPalette[6], cex=1.2,pch=15) ## Square Evoked
## Spontaneous Exploit
datTraj <- datGroupExploitTraj[datGroupExploitTraj$expID == as.character(e$expID.S) & !is.na(datGroupExploitTraj$posX),]
if (NROW(datTraj))
{
idxplot <- seq(1,NROW(datTraj),thin)
points(datTraj[idxplot,]$posX,datTraj[idxplot,]$posY,type="p",col=pairedTrajPalette[7], cex=0.1)
}
## Hunt Episodes Spont Exploitation
datSpotHunts.S.Exploit <- datExploitationHuntEvents[datExploitationHuntEvents$expID == as.character(e$expID.S) & !is.na(datExploitationHuntEvents$expID), ]
points(datSpotHunts.S.Exploit$posX, datSpotHunts.S.Exploit$posY,col=pairedTrajPalette[8], cex=1.2,pch=15) ## Square Evoked
badd <- TRUE
## Add dispersion Time Line + Hunt Events + Norm threshold Threshold
datDisp.S <- datDispersion[datDispersion$expID == as.character(e$expID.S) ,]
datDisp.E <- datDispersion[datDispersion$expID == as.character(e$expID.E) ,]
## Sort by frameRo
datDisp.S <- datDisp.S[order( as.numeric(datDisp.S$frameRow) ), ]
datDisp.E <- datDisp.E[order( as.numeric(datDisp.E$frameRow) ), ]
idxplot.S <- seq(min(1,NROW(datDisp.S)),max(1,NROW(datDisp.S)),thin)
idxplot.E <- seq(min(1,NROW(datDisp.S)),max(1,NROW(datDisp.E)) ,thin)
datDisp.S.frame <- as.numeric(datDisp.S[idxplot.S,]$frameRow)- min((as.numeric(datDisp.S[idxplot.S,]$frameRow) ),na.rm = TRUE ) #datAllFrames[datDisp.S[idxplot.S,]$frameRow,"frameN" ]
datDisp.E.frame <- max(datDisp.S.frame,na.rm=TRUE) + as.numeric(datDisp.E[idxplot.E,]$frameRow)-min(c(as.numeric(datDisp.E[idxplot.E,]$frameRow) ),na.rm = TRUE )
##frameN restarts to 0 for each event so best use frameRow
plot(datDisp.S.frame/G_APPROXFPS ,datDisp.S[idxplot.S,]$Dispersion,type="l" ,ylim=c(0,10),xlim=c(0,max(c(0,datDisp.E.frame),na.rm =TRUE)/G_APPROXFPS ),xlab="(sec)",
ylab="Dispersal (mm)", col=colourDataScheme[[ as.character(e$groupID.S) ]] )
lines(datDisp.E.frame/G_APPROXFPS, datDisp.E[idxplot.E,]$Dispersion,type="l", col=colourDataScheme[[ as.character(e$groupID.E) ]] )
##All Hunt larva hunt events together
datSpotHunts.S <- rbind(datSpotHunts.S.Exploit,datSpotHunts.S.Explore)
datSpotHunts.E <- rbind(datSpotHunts.E.Exploit,datSpotHunts.E.Explore)
##Add Hunt Event ##datDisp.S[datDisp.S$frameRow == datSpotHunts.S$frameRow,]$Dispersion <- fails cause Disp data may be missing at hunt event frame
## Use FrameRow As timepoint sequence - reset to 0 using min(frameRow) for event, and attach Evoked to the back of spontaneous
points( (as.numeric(datSpotHunts.S$frameRow)-min(as.numeric(datDisp.S[idxplot.S,]$frameRow),na.rm=TRUE ) )/G_APPROXFPS, rep(-0.1,times=NROW(datSpotHunts.S$frameN)), cex=1, pch=17)
points( (max(idxplot.S) + as.numeric(datSpotHunts.E$frameRow)-min(as.numeric(datSpotHunts.E$frameRow)))/G_APPROXFPS, rep(-0.1,times=NROW(datSpotHunts.E$frameN)) ,cex=1,pch=17)
##Show Larval Norm Threshold - Draw line
thres_Dispersion_mm <- min((datDisp.E[datDisp.E$Dispersion_larval_norm >= TH_DISP, ] $Dispersion),na.rm=TRUE )
segments(0,thres_Dispersion_mm, max(datDisp.E.frame,na.rm=TRUE)/G_APPROXFPS,
thres_Dispersion_mm,lty=3)
#stopifnot(i < 5)
i <- i+1
} ## For Each Event
}## End of Function
tsec_timeWindow <- 5
```
## Detect Exploration -Exploitation via dispersion
In Marquez et al. 2019 Ext Fig 3a, the dispersion of each larva is normalized against its own range before the overall (bimodal) distribution is shown.
The normalized dispersion distributions of each larva are used to detect the threshold that separates the exploitation and exploration state.
They report (Extended Data Fig. 3a), substantially higher dispersal in the exploration state (9.6 ± 2.5 mm, mean ± s.d., n = 36 animals) than in the exploitation state (2.3 ± 1.3 mm, n = 36 animals).
Using my tracking data I calculated the dispersion at each tracked video frame and plot the distribution to examine if they are bimodal (here using the `r tsec_timeWindow` seconds window).
However, my tracking of each larva is limited to 10 min, and includes only the centre of the arena, but in Marquez et al. 2019 each larva is recorded *for 50-80 min*, while the mean duration of each state is reported to be on average, the *exploitation state persists for 7.1 ± 3.9 min*, and *exploration state persists for 5.5 ± 6.2 min*
(mean ± s.d., n = 36 animals). The duration of each state follows an exponential distribution (λ = 0.17 min−1
for exploitation, λ = 0.22 min−1 for exploration, pooled distribution of n = 36 animals) see (raw data shown on Ext. Fig 7a).
Unfortunatelly with my 10 min recordings for each larvae, it is most likely that I will not observe their behaviour in both states, but likely only observe them in on of these states. This is added ontop the fact that I do not record around the edges of the arena, as they do to see them run around.
Therefore, normalizing and setting a threshold on a per larva basis may not be a good idea.
Perhaps it is best I combine the trajectories of spontaneous and evoked activity for each larva so as to obtain 20min of observation time.
Without normalizing the distribution is shown on the left, and a version normalized per max dispersion measured in each experiment is on the right :
```{r dispersion histograms across groups, fig.show="hold", out.width="33%", echo=FALSE, results='hide' }
loadDispersionData_norm(tsec_timeWindow)
hist(datDispersion$Dispersion,breaks=50,main="(All groups): Dispersion lengths per experiment ",xlab=paste("Dispersion (mm/",tsec_timeWindow,")") )
hist(datDispersion$Dispersion_norm,breaks=50,main="(All groups): Dispersion normalized",xlab="Dispersion (exp. norm) ")
hist(datDispersion$Dispersion_larval_norm ,breaks=50,main="(All groups): Dispersion normalized per larva",xlab="Dispersion (larva norm)")
```
We look at each rearing group separatelly, while combining their evoked and spontaneous conditions
```{r dispersion histograms per group across conditions, fig.show="hold", out.width="33%", echo=FALSE, results='hide' }
hist(datDispersion[datDispersion$groupID %in% c('LE','LL'), ]$Dispersion,breaks=50,main="LF Evoked+Spont.", xlab=paste("Dispersion (mm/",tsec_timeWindow,"s)"),col=colourDataScheme$LF$Evoked)
hist(datDispersion[datDispersion$groupID %in% c('NE','NL'), ]$Dispersion,breaks=50,main="NF Evoked+Spont.",xlab=paste("Dispersion (mm/",tsec_timeWindow,"s)"),col=colourDataScheme$NF$Evoked)
hist(datDispersion[datDispersion$groupID %in% c('DE','DL'), ]$Dispersion,breaks=50,main="DF Evoked+Spont.",xlab=paste("Dispersion (mm/",tsec_timeWindow,"s)"),col=colourDataScheme$DF$Evoked)
```
We then plot each experimental group individually, also examining the dispersion in evoked (in the presence of prey) and spontaneous (no prey) conditions separately.
Next we plot these for each experimental condition individually (non-Normalized):
```{r dispersion histograms per group per condition, fig.show="hold", out.width="33%", echo=FALSE, results='hide' }
#
# ## Normed over all Recorded Dispersions
hist(datDispersion[datDispersion$groupID == 'LE', ]$Dispersion,breaks=100,main="LF Spontaneous", xlab=paste("Dispersion (mm/",tsec_timeWindow,"s)"), col=colourDataScheme$LF$Spont)
hist(datDispersion[datDispersion$groupID == 'NE', ]$Dispersion,breaks=100,main="NF Spontaneous", xlab=paste("Dispersion (mm/",tsec_timeWindow,"s)"), col=colourDataScheme$NF$Spont)
hist(datDispersion[datDispersion$groupID == 'DE', ]$Dispersion,breaks=100,main="DF Spontaneous", xlab=paste("Dispersion (mm/",tsec_timeWindow,"s)"), col=colourDataScheme$DF$Spont)
hist(datDispersion[datDispersion$groupID == 'LL', ]$Dispersion,breaks=100,main="LF Evoked",xlab=paste("Dispersion (mm/",tsec_timeWindow,"s)"), col=colourDataScheme$LF$Evoked)
hist(datDispersion[datDispersion$groupID == 'NL', ]$Dispersion,breaks=100,main="NF Evoked",xlab=paste("Dispersion (mm/",tsec_timeWindow,"s)"), col=colourDataScheme$NF$Evoked)
hist(datDispersion[datDispersion$groupID == 'DL', ]$Dispersion,breaks=100,main="DF Evoked",xlab=paste("Dispersion (mm/",tsec_timeWindow,"s)"), col=colourDataScheme$DF$Evoked)
```
Smooth estimates using a Gaussian kernel show a shift towards exploitation for the pooled *LF* trajectories, measured across the whole event duration (at 1sec intervals):
```{r dispersion densities WholePath per larva-Split E-S, fig.show="hold", out.width="33%", echo=FALSE, results='hide' }
#loadDispersionData_norm(FALSE, tsec_timeWindow )
## plot est, Densities Compare Spont to Evoked
BW=0.5
plot(density(datDispersion[datDispersion$groupID == 'NE', ]$Dispersion, kernel="gaussian",na.rm=TRUE, bw=BW), lwd=4, ylim=c(0,0.7), col=colourDataScheme$NF$Spont,main="NF ",xlab=paste("Dispersion (mm/",tsec_timeWindow,"s)"),lty=1 )
lines(density(datDispersion[datDispersion$groupID == 'NL', ]$Dispersion,kernel="gaussian",na.rm=TRUE,bw=BW),lwd=4,col=colourDataScheme$NF$Evoked,main=NA,lty=2)
legend("topright",c("Spontaneous","Evoked"), lty=c(1,2),col=c(colourDataScheme$NF$Spont,colourDataScheme$NF$Evoked),lwd=3 )
plot(density(datDispersion[datDispersion$groupID == 'LE', ]$Dispersion, kernel="gaussian",na.rm=TRUE,bw=BW), lwd=4, ylim=c(0,0.7),col=colourDataScheme$LF$Spont,main="LF ",xlab=paste("Dispersion (mm/",tsec_timeWindow,"s)"),lty=1 )
lines(density(datDispersion[datDispersion$groupID == 'LL', ]$Dispersion,kernel="gaussian",na.rm=TRUE,bw=BW),lwd=4,col=colourDataScheme$LF$Evoked,main=NA,lty=2 )
legend("topright",c("Spontaneous","Evoked"), lty=c(1,2),col=c(colourDataScheme$LF$Spont,colourDataScheme$LF$Evoked),lwd=3 )
plot(density(datDispersion[datDispersion$groupID == 'DE', ]$Dispersion, kernel="gaussian",na.rm=TRUE,bw=BW),lwd=4, ylim=c(0,0.7),col=colourDataScheme$DF$Spont,main="DF ",xlab=paste("Dispersion (mm/",tsec_timeWindow,"s)"),lty=1 )
lines(density(datDispersion[datDispersion$groupID == 'DL', ]$Dispersion,kernel="gaussian",na.rm=TRUE,bw=BW),lwd=4,col=colourDataScheme$DF$Evoked,main=NA,lty=2 )
legend("topright",c("Spontaneous","Evoked"), lty=c(1,2),col=c(colourDataScheme$DF$Spont,colourDataScheme$DF$Evoked),lwd=3 )
```
These look rather uniform across all groups. But if we examine the dispersion generated over a particular duration time-window, here 20 sec :
```{r dispersion densities 20sec Path per larva-Split E-S, fig.show="hold", out.width="33%", echo=FALSE, results='hide' }
loadDispersionData(TRUE, tsec_timeWindow = 20)
## plot est, Densities Compare Spont to Evoked
BW=0.5
plot(density(datDispersion[datDispersion$groupID == 'NE', ]$Dispersion, kernel="gaussian",na.rm=TRUE, bw=BW), lwd=4, ylim=c(0,0.7), col=colourDataScheme$NF$Spont,main="NF ",xlab="dispersion (mm/20sec)",lty=1 )
lines(density(datDispersion[datDispersion$groupID == 'NL', ]$Dispersion,kernel="gaussian",na.rm=TRUE,bw=BW),lwd=4,col=colourDataScheme$NF$Evoked,main=NA,lty=2)
legend("topright",c("Spontaneous","Evoked"), lty=c(1,2),col=c(colourDataScheme$NF$Spont,colourDataScheme$NF$Evoked),lwd=3 )
plot(density(datDispersion[datDispersion$groupID == 'LE', ]$Dispersion, kernel="gaussian",na.rm=TRUE,bw=BW), lwd=4, ylim=c(0,0.7),col=colourDataScheme$LF$Spont,main="LF ",xlab="Dispersion (mm/20sec)",lty=1 )
lines(density(datDispersion[datDispersion$groupID == 'LL', ]$Dispersion,kernel="gaussian",na.rm=TRUE,bw=BW),lwd=4,col=colourDataScheme$LF$Evoked,main=NA,lty=2 )
legend("topright",c("Spontaneous","Evoked"), lty=c(1,2),col=c(colourDataScheme$LF$Spont,colourDataScheme$LF$Evoked),lwd=3 )
plot(density(datDispersion[datDispersion$groupID == 'DE', ]$Dispersion, kernel="gaussian",na.rm=TRUE,bw=BW),lwd=4, ylim=c(0,0.7),col=colourDataScheme$DF$Spont,main="DF ",xlab="Dispersion (mm/20sec)",lty=1 )
lines(density(datDispersion[datDispersion$groupID == 'DL', ]$Dispersion,kernel="gaussian",na.rm=TRUE,bw=BW),lwd=4,col=colourDataScheme$DF$Evoked,main=NA,lty=2 )
legend("topright",c("Spontaneous","Evoked"), lty=c(1,2),col=c(colourDataScheme$DF$Spont,colourDataScheme$DF$Evoked),lwd=3 )
```
<!-- For completness, the following dispersions have been normalized to maximum trajectory dispersion found across all experiments (*global normalization*): -->
```{r plot globally normalized dispersion distributions, fig.show="hold", out.width="33%", echo=FALSE, results='hide',include=FALSE,eval=FALSE }
# ## Normed over all Recorded Dispersions
hist(datDispersion[datDispersion$groupID == 'LE', ]$Dispersion/AllRange[2],breaks=100,main="LF Spontaneous",xlab="Dispersion (global norm. )")
hist(datDispersion[datDispersion$groupID == 'NE', ]$Dispersion/AllRange[2],breaks=100,main="NF Spontaneous",xlab="Dispersion (global norm. )")
hist(datDispersion[datDispersion$groupID == 'DE', ]$Dispersion/AllRange[2],breaks=100,main="DF Spontaneous",xlab="Dispersion (global norm. )")
hist(datDispersion[datDispersion$groupID == 'LL', ]$Dispersion/AllRange[2],breaks=100,main="LF Evoked",xlab="Dispersion (global norm. .)")
hist(datDispersion[datDispersion$groupID == 'NL', ]$Dispersion/AllRange[2],breaks=100,main="NF Evoked",xlab="Dispersion (global norm. )")
hist(datDispersion[datDispersion$groupID == 'DL', ]$Dispersion/AllRange[2],breaks=100,main="DF Evoked",xlab="Dispersion (global norm. )")
```
Here differences in LF having larger dispersion within the 20sec time-frame are evident, combined with the results of theprevious figures on dispersion over the whole path being uniform, these results imply **LF do not explore the ROI with higher dispersal, but they are quicker to disperse**.
*In the absence of prey, dispersions grow faster in LF and DF*.
### Normalized dispersion per experiment
Next, we examine the same dispesions normalized against the maximum dispersion calculated in the trajectory length of the respective experiment.
Each measured dispersion is divided by the max dispersion trajectory experiment,
(ie for each larva this can be different in evoked or spontaneous conditions).
```{r plot normalized dispersion distributions, fig.show="hold", out.width="33%", echo=FALSE, results='hide' , warning=FALSE}
### Normed Per Larva
datDispersion <- loadDispersionData_norm(tsec_timeWindow)
strXLab <- paste(tsec_timeWindow,"sec Dispersion (norm per exp.)")
hist(datDispersion[datDispersion$groupID == 'LE', ]$Dispersion_norm,breaks=50,main="LF Spontaneous",xlab=strXLab, col=colourDataScheme$LF$Spont)
hist(datDispersion[datDispersion$groupID == 'NE', ]$Dispersion_norm,breaks=50,main="NF Spontaneous",xlab=strXLab, col=colourDataScheme$NF$Spont)
hist(datDispersion[datDispersion$groupID == 'DE', ]$Dispersion_norm,breaks=50,main="DF Spontaneous",xlab=strXLab, col=colourDataScheme$DF$Spont)
hist(datDispersion[datDispersion$groupID == 'LL', ]$Dispersion_norm,breaks=50,main="LF Evoked",xlab=strXLab,col=colourDataScheme$LF$Evoked)
hist(datDispersion[datDispersion$groupID == 'NL', ]$Dispersion_norm,breaks=50,main="NF Evoked",xlab=strXLab,col=colourDataScheme$NF$Evoked)
hist(datDispersion[datDispersion$groupID == 'DL', ]$Dispersion_norm,breaks=50,main="DF Evoked",xlab=strXLab,col=colourDataScheme$DF$Evoked)
```
### Normalized dispersion per larva combined test conditions
Because each larva is recorded in two conditions, and as Marquez et al 2019 report that the foraging state switching can be seen intact both in the presence and in the absence of prey , we may then combine our spontaneous and evoked condition recordings and treat them as a single unit, thus allowing us to normalize each larvas trajectories to the max dispersion found across both its test conditions. In this manner each larva's dispersion is examined across a 20min recording session.
```{r dispersion histogram normalized per larva, fig.show="hold", out.width="33%", echo=FALSE, results='hide' }
### Dispesions distributions Normalized on Per Larva basis -
tsec_timeWindow <-5
datDispersion <- loadDispersionData_norm(tsec_timeWindow)
hist(datDispersion[datDispersion$groupID %in% c('LE','LL'), ]$Dispersion_larval_norm, breaks=100,main="LF S+E ",xlab="Dispersion (norm per larva)")
hist(datDispersion[datDispersion$groupID %in% c('NE','NL'), ]$Dispersion_larval_norm, breaks=100,main="NF S+E",xlab="Dispersion (norm per larva)")
hist(datDispersion[datDispersion$groupID %in% c('DE','DL'), ]$Dispersion_larval_norm, breaks=100,main="DF S+E",xlab="Dispersion (norm per larva)")
```
#### Histograms of normalized dispersion per larva, split S-E conditions
Separating Spontaneous from Evoked Conditions we see a potential shift toward lower dispersion in the presence of prey:
```{r dispersion histogram normalized per larva-Split E-S, fig.show="hold", out.width="50%", echo=FALSE, results='hide' }
### Dispesions distributions Normalized on Per Larva basis -
hist(datDispersion[datDispersion$groupID %in% c('LE'), ]$Dispersion_larval_norm, breaks=100,main="LF Spont ", xlab="Dispersion (norm per larva)",col=colourDataScheme$LF$Spont)
hist(datDispersion[datDispersion$groupID %in% c('LL'), ]$Dispersion_larval_norm, breaks=100,main="LF Evoked ",xlab="Dispersion (norm per larva)",col=colourDataScheme$LF$Evoked)
hist(datDispersion[datDispersion$groupID %in% c('NE'), ]$Dispersion_larval_norm, breaks=100,main="NF Spont ", xlab="Dispersion (norm per larva)",col=colourDataScheme$NF$Spont)
hist(datDispersion[datDispersion$groupID %in% c('NL'), ]$Dispersion_larval_norm, breaks=100,main="NF Evoked ",xlab="Dispersion (norm per larva)", col=colourDataScheme$NF$Evoked)
hist(datDispersion[datDispersion$groupID %in% c('DE'), ]$Dispersion_larval_norm, breaks=100,main="DF Spont ", xlab="Dispersion (norm per larva)",col=colourDataScheme$DF$Spont)
hist(datDispersion[datDispersion$groupID %in% c('DL'), ]$Dispersion_larval_norm, breaks=100,main="DF Evoked ",xlab="Dispersion (norm per larva)",col=colourDataScheme$DF$Evoked)
```
#### Density estimation normalized dispersion per larva - compare Evoked to Spontaneous
Next I estimated densities using a gaussian kernel, allowing direct comparison between test conditions shows LF dispersions are modified by the presence of prey.
```{r dispersion densities normalized per larva-Split E-S, fig.show="hold", out.width="33%", echo=FALSE, results='hide' }
## plot est, Densities Compare Spont to Evoked
BW=0.05
ylimUp <- 5
plot(density(datDispersion[datDispersion$groupID == 'NE', ]$Dispersion_larval_norm, kernel="gaussian",na.rm=TRUE, bw=BW), lwd=4, ylim=c(0,ylimUp), col=colourDataScheme$NF$Spont,main="NF ",xlab="Dispersion (norm. per larva)",lty=1 )
lines(density(datDispersion[datDispersion$groupID == 'NL', ]$Dispersion_larval_norm,kernel="gaussian",na.rm=TRUE,bw=BW),lwd=4,col=colourDataScheme$NF$Evoked,main=NA,lty=2)
legend("topright",c("Spontaneous","Evoked"), lty=c(1,2),col=c(colourDataScheme$NF$Spont,colourDataScheme$NF$Evoked),lwd=3 )
plot(density(datDispersion[datDispersion$groupID == 'LE', ]$Dispersion_larval_norm, kernel="gaussian",na.rm=TRUE,bw=BW), lwd=4, ylim=c(0,ylimUp),col=colourDataScheme$LF$Spont,main="LF ",xlab="Dispersion (norm. per larva)",lty=1 )
lines(density(datDispersion[datDispersion$groupID == 'LL', ]$Dispersion_larval_norm,kernel="gaussian",na.rm=TRUE,bw=BW),lwd=4,col=colourDataScheme$LF$Evoked,main=NA,lty=2 )
legend("topright",c("Spontaneous","Evoked"), lty=c(1,2),col=c(colourDataScheme$LF$Spont,colourDataScheme$LF$Evoked),lwd=3 )
plot(density(datDispersion[datDispersion$groupID == 'DE', ]$Dispersion_larval_norm, kernel="gaussian",na.rm=TRUE,bw=BW),lwd=4, ylim=c(0,ylimUp),col=colourDataScheme$DF$Spont,main="DF ",xlab="Dispersion (norm. per larva)",lty=1 )
lines(density(datDispersion[datDispersion$groupID == 'DL', ]$Dispersion_larval_norm,kernel="gaussian",na.rm=TRUE,bw=BW),lwd=4,col=colourDataScheme$DF$Evoked,main=NA,lty=2 )
legend("topright",c("Spontaneous","Evoked"), lty=c(1,2),col=c(colourDataScheme$DF$Spont,colourDataScheme$DF$Evoked),lwd=3 )
```
#### Maximum dispersion per larva
Then examining the maximum larval dispersions over the full event path, we find they look similar between groups :
I will use these max values to normalize dispersions for each larva (as in Marquez et al 2019).
#### Compare distribution of max dispersion per larva
Full Path:
```{r Max-dispersion histogram plots, fig.show="hold", out.width="50%", echo=FALSE, results='hide',fig.cap="Histograms of max dispersion per larva using the full event trajectories - No time sliding time window, and 20sec duration paths" }
##### Maximum Dispersions Per Larva-
hist_MaxDispersionPerLarva <- function(tsec_timeWindow)
{
XLIM <- c(0,15)
strFileName <- paste0(strDataExportDir,"/foragingState_max_Dispersion_perLarva_",tsec_timeWindow,"sec.rds")
datMaxDispersionPerLarva <- data.frame() ##init Variable
message("Loading max disp precalc :",strFileName)
if (file.exists(strFileName))
datMaxDispersionPerLarva <- readRDS(file=strFileName )
else{
## Make missing File
datDispersion <- loadDispersionData_norm(tsec_timeWindow)
mergeRangeOfLarvalDispersionPerLarvaOntoDispersion(datDispersion,datExpPairs,tsec_timeWindow)
datMaxDispersionPerLarva <- readRDS(file=strFileName ) ##Attempt Load Again
}
nBreaks=seq(0,13,1)
ylimUp <- 35
## Max reported is across NE/NL - so checking either condition would suffice to get the max for each larva
datMaxDispersionPerLarva.LF <- datMaxDispersionPerLarva[datMaxDispersionPerLarva$expID %in% datExpPairs[datExpPairs$groupID.S == 'LE' ,]$expID.S, ]$max_larval_Dispersion
datMaxDispersionPerLarva.NF <- datMaxDispersionPerLarva[datMaxDispersionPerLarva$expID %in% datExpPairs[datExpPairs$groupID.S == 'NE' ,]$expID.S, ]$max_larval_Dispersion
datMaxDispersionPerLarva.DF <- datMaxDispersionPerLarva[datMaxDispersionPerLarva$expID %in% datExpPairs[datExpPairs$groupID.S == 'DE' ,]$expID.S, ]$max_larval_Dispersion
# plot histograms
datMaxDispersionPerLarva.NF_hist <- hist((datMaxDispersionPerLarva.NF),breaks=nBreaks, plot=FALSE)
datMaxDispersionPerLarva.LF_hist <- hist((datMaxDispersionPerLarva.LF) ,breaks=nBreaks, plot=FALSE)
datMaxDispersionPerLarva.DF_hist <- hist((datMaxDispersionPerLarva.DF) ,breaks=nBreaks, plot=FALSE)
plot(datMaxDispersionPerLarva.NF_hist$mids,datMaxDispersionPerLarva.NF_hist$counts,
main=paste("Histogram of max-dispersal per larva ",tsec_timeWindow,"sec"),
xlab="Max. dispersion per larva (mm)", xlim=XLIM,
ylab="Number of larvae",
pch=pointTypeScheme$NL, lty=lineTypeL.NF,
col=colourDataScheme$NF$Evoked, ylim=c(0,ylimUp),type="b")
points(datMaxDispersionPerLarva.NF_hist$mids,datMaxDispersionPerLarva.LF_hist$counts,
xlim=XLIM, pch=pointTypeScheme$LL, col=colourDataScheme$LF$Evoked,lty=lineTypeL.LF, ylim=c(0,ylimUp),type="b")
points(datMaxDispersionPerLarva.DF_hist$mids,datMaxDispersionPerLarva.DF_hist$counts, lty=lineTypeL.DF,
xlim=XLIM,pch=pointTypeScheme$DL,
col=colourDataScheme$DF$Evoked, ylim=c(0,ylimUp),type="b")
legend("topleft",c("NF","LF","DF"),pch=c(pointTypeScheme$NL,pointTypeScheme$LL,pointTypeScheme$DL) , lty=c(lineTypeL.NF,lineTypeL.LF,lineTypeL.DF),col=c(colourDataScheme$NF$Evoked,colourDataScheme$LF$Evoked,colourDataScheme$DF$Evoked),lwd=3 )
return(datMaxDispersionPerLarva)
}
datMaxDispersionPerLarva_All <- hist_MaxDispersionPerLarva(0)
datMaxDispersionPerLarva_5sec <-hist_MaxDispersionPerLarva(5)
datMaxDispersionPerLarva_20sec <-hist_MaxDispersionPerLarva(10)
```
```{r max-dispersion densities compare groups, fig.show="hold", out.width="50%", echo=FALSE, cache=TRUE,eval=FALSE }
## plot est, Densities Compare Spont to Evoked
pBW <- 0.3
ylimUp <- 1
plot(density(datMaxDispersionPerLarva.NF, kernel="gaussian",na.rm=TRUE, bw=pBW), lwd=4, ylim=c(0,ylimUp), col=colourDataScheme$NF$Evoked,main="Maximum Dispersion Per Larva ",xlab="Dispersion (mm)",lty=lineTypeL.NF )
lines(density((datMaxDispersionPerLarva.LF), kernel="gaussian",na.rm=TRUE,bw=pBW), lwd=4, ylim=c(0,ylimUp),col=colourDataScheme$LF$Evoked,main=NA,xlab=NA,lty=lineTypeL.LF )
lines(density((datMaxDispersionPerLarva.DF), kernel="gaussian",na.rm=TRUE,bw=pBW),lwd=4, ylim=c(0,ylimUp),col=colourDataScheme$DF$Evoked,main=NA,xlab=NA,lty=lineTypeL.DF )
```
##### Compare max dispersion distributions between conditions
It appears that the max dispersions do not differ much between spontaneous and evoked conditions for the DF group,
while there seems to be some evidence that LF Larvae explore more in the absence of prey and perhaps,suprisingly, NF larvae explore less in the absence of prey.
Maybe these could make sense under an expected reward paradigm, given experience.
```{r max-dispersion per larva densities split conditions, fig.show="hold", out.width="33%", echo=FALSE, cache=FALSE }
## plot est, Densities Compare Spont to Evoked
datMaxDispersionPerLarva <- datMaxDispersionPerLarva_20sec
# # extract Evoked to Spont max disp data
datMaxDispersionPerExp.NF.Spont <- datMaxDispersionPerLarva[datMaxDispersionPerLarva$expID %in% datExpPairs[datExpPairs$groupID.S == 'NE' ,]$expID.S, ]$max_exp_Dispersion
datMaxDispersionPerExp.NF.Evoked <- datMaxDispersionPerLarva[datMaxDispersionPerLarva$expID %in% datExpPairs[datExpPairs$groupID.E == 'NL' ,]$expID.E, ]$max_exp_Dispersion
datMaxDispersionPerExp.LF.Spont <- datMaxDispersionPerLarva[datMaxDispersionPerLarva$expID %in% datExpPairs[datExpPairs$groupID.S == 'LE' ,]$expID.S, ]$max_exp_Dispersion
datMaxDispersionPerExp.LF.Evoked <- datMaxDispersionPerLarva[datMaxDispersionPerLarva$expID %in% datExpPairs[datExpPairs$groupID.E == 'LL' ,]$expID.E, ]$max_exp_Dispersion
datMaxDispersionPerExp.DF.Spont <- datMaxDispersionPerLarva[datMaxDispersionPerLarva$expID %in% datExpPairs[datExpPairs$groupID.S == 'DE' ,]$expID.S, ]$max_exp_Dispersion
datMaxDispersionPerExp.DF.Evoked <- datMaxDispersionPerLarva[datMaxDispersionPerLarva$expID %in% datExpPairs[datExpPairs$groupID.E == 'DL' ,]$expID.E, ]$max_exp_Dispersion
ylimUp <- 0.5
pBW <- 1
plot(density(datMaxDispersionPerExp.NF.Spont, kernel="gaussian",na.rm=TRUE, bw=pBW), lwd=4, ylim=c(0,ylimUp), col=colourDataScheme$NF$Spont,main="NF Trajectories ",xlab="Max Dispersion (mm)",lty=1 )
lines(density(datMaxDispersionPerExp.NF.Evoked,kernel="gaussian",na.rm=TRUE,bw=pBW),lwd=4,col=colourDataScheme$NF$Evoked,main=NA,lty=2)
legend("topright",c("Spontaneous","Evoked"), lty=c(1,2),col=c(colourDataScheme$NF$Spont,colourDataScheme$NF$Evoked),lwd=3 )
plot(density(datMaxDispersionPerExp.LF.Spont, kernel="gaussian",na.rm=TRUE,bw=pBW), lwd=4, ylim=c(0,ylimUp),col=colourDataScheme$LF$Spont,main="LF Trajectories",xlab="Max Dispersion (mm)",lty=1 )
lines(density(datMaxDispersionPerExp.LF.Evoked,kernel="gaussian",na.rm=TRUE,bw=pBW),lwd=4,col=colourDataScheme$LF$Evoked,main=NA,lty=2 )
legend("topright",c("Spontaneous","Evoked"), lty=c(1,2),col=c(colourDataScheme$LF$Spont,colourDataScheme$LF$Evoked),lwd=3 )
plot(density(datMaxDispersionPerExp.DF.Spont, kernel="gaussian",na.rm=TRUE,bw=pBW),lwd=4, ylim=c(0,ylimUp),col=colourDataScheme$DF$Spont,main="DF Trajectories",xlab="max Dispersion (mm)",lty=1 )
lines(density(datMaxDispersionPerExp.DF.Evoked,kernel="gaussian",na.rm=TRUE,bw=pBW),lwd=4,col=colourDataScheme$DF$Evoked,main=NA,lty=2 )
legend("topright",c("Spontaneous","Evoked"), lty=c(1,2),col=c(colourDataScheme$DF$Spont,colourDataScheme$DF$Evoked),lwd=3 )
```
## Path length and dispersion ratio distributions
Within Low dispersions hides a locomotive behaviour of pause, where the larva is not actually moving. We want to explore how experience modifies their locomotion strategy and thus this is best done by examining dispersion in relation to the distance travelled. Particularly I will look into a a state of locomotion pause, when the larva stop moving.
Thus, similar to the measure of dispersion, we plot the 5sec recent trajectory lengths over all movement and over hunt event initiations, side by side:
### Distributions of path length
```{r length histograms per group across conditions, fig.show="hold", out.width="50%", echo=FALSE, results='hide' }
tsec_timeWindow <- 5
datDispersion <- loadDispersionData(F,tsec_timeWindow)
xbreaks <-seq(0,max(datDispersion$Length,na.rm=TRUE)+2,2)
datHEventDispersion <- loadHuntEventMergedWithPathStat(tsec_timeWindow)
h_Length_NE <- hist(datDispersion[datDispersion$groupID %in% c('NE'), ]$Length,breaks=xbreaks,main="NF Spont.",xlab="Length (mm)",col=colourDataScheme$NF$Spont)
h_Length_NL <- hist(datDispersion[datDispersion$groupID %in% c('NL'), ]$Length,breaks=xbreaks,main="NF Evoked.",xlab="Length (mm)",col=colourDataScheme$NF$Evoked)
h_Length_LE <- hist(datDispersion[datDispersion$groupID %in% c('LE'), ]$Length,breaks=xbreaks,main="LF Spont.",xlab="Length (mm)",col=colourDataScheme$LF$Spont)
h_Length_LL <- hist(datDispersion[datDispersion$groupID %in% c('LL'), ]$Length,breaks=xbreaks,main="LF Evoked.",xlab="Length (mm)",col=colourDataScheme$LF$Evoked)
h_Length_DE <- hist(datDispersion[datDispersion$groupID %in% c('DE'), ]$Length,breaks=xbreaks,main="DF Spont.",xlab="Length (mm)",col=colourDataScheme$DF$Spont)
h_Length_DL <- hist(datDispersion[datDispersion$groupID %in% c('DL'), ]$Length,breaks=xbreaks,main="DF Evoked.",xlab="Length (mm)",col=colourDataScheme$DF$Evoked)
hist(datHEventDispersion[datHEventDispersion$groupID=='NE', ]$Length,breaks=xbreaks,main="NF Spont Hunt-events",xlab="Length",col=colourDataScheme$NF$Spont)
hist(datHEventDispersion[datHEventDispersion$groupID=='NL', ]$Length,breaks=xbreaks,main="NF Evoked Hunt-events",xlab="Length",col=colourDataScheme$NF$Evoked)
hist(datHEventDispersion[datHEventDispersion$groupID=='LE', ]$Length,breaks=xbreaks,main="LF Spont Hunt-events",xlab="Length ",col=colourDataScheme$LF$Spont)
hist(datHEventDispersion[datHEventDispersion$groupID=='LL', ]$Length,breaks=xbreaks,main="LF Evoked Hunt-events",xlab="Length ",col=colourDataScheme$LF$Evoked)
hist(datHEventDispersion[datHEventDispersion$groupID=='DE', ]$Length,breaks=xbreaks,main="DF Spont Hunt-events",xlab="Length",col=colourDataScheme$DF$Spont)
hist(datHEventDispersion[datHEventDispersion$groupID=='DL', ]$Length,breaks=xbreaks,main="DF Evoked Hunt-events",xlab="Length",col=colourDataScheme$DF$Evoked)
```
Comparing between general and hunt-event lengths it appears:
- path lengths can be bimodal, like dispersions, in spontaneous conditions
- LF Show higher motility to controls in both conditions
- LF Spont. Shows overal higher motility to controls- Low occupancy in small movement mode
- Locomotion in Evoked conditions shows higher motility, and motion range, than Spontaneous.
- Evoked Hunt events occur over the shorter movement sub-range/mode of the overall distribution
To better examine tendencies to move towards dispersing trajectories we need to account for the effect of general motion, ie the length of a trajectory.
Here I examine recent dispersion as a ratio of recent trajectory length (5 sec window). A ration of 0.5 means larva moved in a straight line, as dispersal is the *radius* not the diameter of the circle encompassing the recent trajectory
I next plot on logarithmic scale the percentage of each Path length and try to see if a power law like regime exists in the distribution, but also if the presence of prey changes the linear - drop off regime of the distribution. This is inspired by Fig 3 from Viswanathan et al 1999
```{r length log distributions conditions, fig.show="hold", out.width="50%", echo=FALSE, results='hide' ,warning=FALSE }
#,log="xy"
lLinModel_NE <- getLogPowerSlope(h_Length_NE,10)
lLinModel_NL <- getLogPowerSlope(h_Length_NL,10)
plot(log10(h_Length_NE$mids),log10(100*h_Length_NE$counts/sum(h_Length_NE$counts) ),main=paste("NF Log-Log percentage of lengths " ),xlab="log Length (mm)",col=colourDataScheme$NF$Spont,pch=16,xlim=c(0,2.5),ylim=c(-4,3), ylab="log N(l) %")
points(log10(h_Length_NL$mids),log10(100*h_Length_NL$counts/sum(h_Length_NL$counts) ),
#main=paste("NF Evoked. mu:",getLogPowerSlope(h_Length_NL)),
xlab="Length (mm)",col=colourDataScheme$NF$Evoked,pch=16)
lines(lLinModel_NE$ptx_line,lLinModel_NE$pty_line,lwd=3,col=colourDataScheme$NF$Spont)