-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.R
1590 lines (1312 loc) · 53.6 KB
/
functions.R
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
#---------------------------------------------------------------------
#
# REM612 Project Script - functions
#
# Author: Samuel Johnson
# Date: 19/1/15
#
# This script contains the functions for the simulation model project
#
#---------------------------------------------------------------------
# Source mseRtools for useful functions - all hail lisread
source ( "mseRtools.r" )
# The following function creates a transition matrix for a rectangular grid
# where the point will migrate towards the left edge of the grid on
# average and have non-zero probability of a stationary step.
# Args: r = number of rows
# c = number of columns
#
# Returns: westStatMat = transition matrix
westStatMat <- function ( r = rows, c = cols)
{
# The transition matrix is square with dimension r*c
dim <- r*c
# First create the matrix of zeroes
transMat <- matrix ( data = 0, nrow = dim, ncol = dim )
## Then we need to populate the matrix of probabilities.
## First the corners of the grid, except the left corners
# Top right
transMat [ c,
c ( c - 1,
2 * c - 1,
c, 2 * c ) ] <- rep ( x = c(2./6., 1./6. ),
times = c( 2, 2 ) )
# Lower right
transMat [ dim,
c( dim, dim - c,
dim - 1, dim - 1 - c ) ] <- rep ( x = c(1./6., 2./6. ),
times = c( 2, 2 ) )
## Now the edges of the grid
# Top edge
for (i in 2:( c - 1) ){
transMat [ i, c ( (i-1):(i+1),
(i+c-1):(i+c+1) ) ] <- rep ( x = c ( 1./3.,
1./12.,
1./12. ),
times = 2 )
}
# Bottom edge
for (i in (dim-c+2):(dim-1) ) {
transMat [ i,
c( (i-1):(i+1),
(i-c-1):(i-c+1) ) ] <- rep ( x = c ( 1./3.,
1./12.,
1./12. ),
times = 2 )
}
# Left edge
leftEdge <- seq ( from = 1, to = dim-c+1, by = c )
for ( i in leftEdge ) {
transMat [ i, i ] <- 1
}
# Right edge
rightEdge <- seq (from = (2*c), to = (dim - c), by = c )
for ( i in rightEdge ) {
transMat [ i, c( i-c,
i-c-1,
i, i-1, i+c, i+c-1 ) ] <- rep ( x = c( 1./9., 2./9.),
times = 3 )
}
## Now the interior cells
for ( i in 2:(r-1) ) {
for (j in 2:(c-1) ) {
s <- (i - 1) * c + j
transMat[ s, c( (s-c-1):(s-c+1),
(s-1):(s+1),
(s+c-1):(s+c+1) ) ] <- rep ( x = c ( 2./9.,
1./18.,
1./18. ),
times = 3 )
}
}
return(transMat)
}
# This function creates a matrix of transition probabilities for a markov
# chain on a rectangular grid with equal probability of moving to any nearest
# neighbour cell or staying put.
# Args: r = number of rows
# c = number of columns
#
# Returns: transMat = transition matrix
simpleStatMat <- function ( r = rows, c = cols )
{
# The transition matrix is square with dim = r*c
dim <- r*c
# First create the matrix of zeroes
transMat <- matrix ( data = 0, nrow = dim, ncol = dim )
## Then we need to populate the matrix of probabilities.
## First the corners of the grid
# Top left
transMat [ 1, c( 1, 2, c + 1, c + 2 ) ] <- rep ( x = 0.25, times = 4 )
# Top right
transMat [ c,
c ( c,
c - 1,
2 * c - 1, 2 * c - 2 ) ] <- rep ( x = 0.25, times = 4 )
# Lower left
# create a variable for the lower left corner
llc <- dim - c + 1
transMat [ llc ,
c( llc, llc + 1, llc - c, llc - c + 1 ) ] <- rep ( x = 0.25,
times = 4 )
# Lower right
transMat [ dim,
c( dim, dim - 1, dim - 1 - c, dim - c ) ] <- rep ( x = 0.25,
times = 4 )
## Now the edges of the grid
# Top edge
for (i in 2:( c - 1) ){
transMat [ i, c ( (i-1):(i+1),
(i+c-1):(i+c+1) ) ] <- rep ( x = 1./6., times = 6 )
}
# Bottom edge
for (i in (dim-c+2):(dim-1) ) {
transMat [ i, c( (i-1):(i+1), (i-c-1):(i-c+1) ) ] <- rep ( x = 1./6.,
times = 6 )
}
# Left edge
leftEdge <- seq ( from = c+1, to = dim-2*c+1, by = c )
for ( i in leftEdge ) {
transMat [ i, c ( i-c, i-c+1, i, i+1, i+c, i+c+1 ) ] <- rep ( x = 1./6.,
times = 6 )
}
# Right edge
rightEdge <- seq (from = (2*c), to = (dim - c), by = c )
for ( i in rightEdge ) {
transMat [ i, c( i-c, i-c-1, i, i-1, i+c, i+c-1 ) ] <- rep ( x = 1./6.,
times = 6 )
}
## Now the interior cells
for ( i in 2:(r-1) ) {
for (j in 2:(c-1) ) {
s <- (i - 1) * c + j
transMat[ s, c( (s-c-1):(s-c+1),
(s-1):(s+1),
(s+c-1):(s+c+1) ) ] <- rep ( x = 1./9., times = 9 )
}
}
return(transMat)
}
# The following function will simulate a pair of parallel markov processes,
# a fish and a boat, moving around on a rectangular grid. The fish is
# acoustically tagged, and the function returns the number of times the boat
# succesfully detected the fish when they were in the same cell, with a given
# probablity of detection.
# Args: r = rows of the grid
# c = columns of the grid
# detProb = probability of detection
# nT = number of time steps
# print = boolean of whether to print the number of detections
#
# Returns: d = number of detections
simpleSim <- function ( r = rows, c = cols, nBoats = 1,
detProb = p, nT = nT, print = TRUE )
{
# Create transition matrix
transitions <- simpleStatMat ( r = r, c = c )
# make into a Markov Chain
gridMC <- new ( "markovchain",
transitionMatrix = transitions, name = "gridMC" )
## Simulate a boat and a fish as two parallel markov processes
# The fishing boats
# Create a matrix to hold fishing boats
B <- matrix ( data = 0, nrow = nT, ncol = nBoats )
# For loop to fill matrix
for (boat in 1:nBoats) {
B[ , boat ] <- as.numeric ( rmarkovchain ( n = nT, object = gridMC ) )
}
# The tagged fish
F <- as.numeric ( rmarkovchain ( n = nT, object = gridMC ) )
## Now to use this to simulate detection using the detection efficiency
# First, find the number of encounters between each boat and the fish
opp <- length ( which ( B - F == 0 ) )
# Then count the number of detections, using the probability of detection p
d <- rbinom ( n = 1, size = opp, prob = p )
# print the number of detections if asked
if ( print ) {
cat ( "The fish was detected by the boat", d, "times. \n", sep = " " )
}
# return the number of detections
return ( d )
}
# This function converts body lengths per second into km/hr for a fish
# of a given length
# Args: blSpeed = ave. number of body lengths per second a fish swims
# fLength = length of fish
# Returns: speed = ave speed in km/hr
speedConv <- function ( blSpeed = 0.6, fLength = 0.55 )
{
# compute m/s
msVelocity <- blSpeed * fLength
# Convert to km/hr
kmh <- msVelocity * 3.6
# return
return ( kmh )
}
# This function converts a cartesian ordered pair into a polar ordered pair
# Args: x = x-value
# y = y-value
# Rets:
# (r,t) = (radius, angle)
cart2pol <- function ( x = 1, y = 1 )
{
# Convert to a complex number
z <- complex ( real = x, imaginary = y )
# Extract radius and angle
r <- Mod ( z )
t <- Arg ( z )
# return
return ( c ( r, t ) )
}
# This function converts a polar ordered pair into a cartesian ordered pair
# Args: r = radius
# t = angle
# Rets:
# (x,y) = cartesian coords of point
pol2cart <- function ( r = 1, t = 0 )
{
# convert to complex number
z <- complex ( modulus = r, argument = t )
# Extract real and imaginary parts
x <- Re ( z )
y <- Im ( z )
# Return ordered pair
return ( c ( x, y ) )
}
# The function delta is for making a discrete time markov chain. This
# function takes a current location, grid dimensions and a transition matrix
# and returns a new location based.
# Arguments: loc = grid cell number of current location
# r = number of rows in grid
# c = number of columns in grid
# probs = transition matrix of probabilities
#
# Returns delta = difference in grid refs of old and new locations
delta <- function ( loc = 1, r = r, c = c, probs = transMat )
{
# Compute number of grid cells
dim <- r*c
if ( loc != 0 )
{
# delta ( location ) = sample ( grid cells, prob = transMat[location,] )
newLoc <- sample ( x = 1:dim, size = 1, prob = probs [ loc, ] )
# Find difference between new and old grid refs
delta <- newLoc - loc
} else { # loc = 0 means the fish hasn't entered grid yet.
delta <- 0
}
# return difference
return ( delta )
}
# The following function creates a matrix in which the rows are discrete
# time markov chains for fish movement through a grid.
# Arguments: r = rows of movement grid
# c = cols of movement grid
# nFish = number of fish to simulate
# nT = number of time steps
#
# Returns: M = matrix with MCs of movement as rows
fishPathsOld <- function ( r = rows, c = cols, nFish = nF, nT = nT,
entryCells = inlets )
{
# Generate transition matrix
transMat <- westStatMat ( r = r, c = c )
# Create matrix to hold fish paths
F <- matrix ( data = 0, nrow = nFish, ncol = nT )
# Set random entry time for each fish
entryTime <- sample ( x = 1:nT, replace = TRUE, size = nF )
# Choose initial locations along the right hand edge (4 inlets) for each fish
# Needs to be turned into an apply function - might be worth turning
# F into a ragged array and using tapply.
for ( f in 1:nF )
{
F [ f , entryTime [ f ] ] <- sample ( x = entryCells,
size = 1 )
}
# run simulation forward for each fish, choosing next location
# based on current location and the transition matrix - can't be
# parallelised as not independent
for ( t in 1:(nT - 1) )
{
# The following is a little arcane. If the fish hasn't entered yet
# F[ , t + 1] might be non-zero, but F[,t] and delta will be zero. If
# the fish has entered, then F[,t] and delta are non-zero, but F[,t+1]
# is zero. Thus, while there are too many terms in the sum, it works out.
F [ , t+1 ] <- F [ , t + 1 ] +
F [ , t ] +
sapply ( X = F[ , t ], FUN = delta, r = r, c = c,
probs = transMat )
}
# Return fish paths
return ( F )
}
# The following function creates a matrix in which the rows are discrete
# time markov chains for fish movement through a grid.
# Arguments: nFish = number of fish to simulate
# nT = number of time steps
# entryLocs = matrix with lat/long of initial positions
# sigma = sd of process error
# wgt = multiplicative parameter for potential function
# bathy = list of lat, long vectors and depth matrix
# Returns: P = 3D array of lat, long in time for each fish
fishPaths <- function ( nFish = nF, nT = nT, entryLocs = inlets,
sigmaD = distSD, sigmaT = sigmaTheta, meanD = 0.01,
bathy = bathyGrad, potPoint = potentialPoint )
{
# Create matrix to hold fish paths
P <- array ( data = 0, dim = c ( nFish, 2, nT ) )
# Choose initial locations along the right hand edge (4 inlets) for each fish
# Needs to be turned into an apply function - might be worth turning
# F into a ragged array and using tapply.
initLoc <- sample ( x = 1:4, size = nF, replace = TRUE )
P [ ,1:2,1] <- entryLocs [ initLoc, ]
# run simulation forward for each fish, choosing next location
# based on current location and the transition matrix - can't be
# parallelised as not independent
# Make a cluster
clust <- makeCluster ( spec = nCores )
for ( t in 1:( nT - 1 ) )
{
# The following is a little arcane. If the fish hasn't entered yet
# F[,,t + 1] might be non-zero, but F[,,t] and delta will be zero. If
# the fish has entered, then F[,,t] and delta are non-zero, but F[,,t+1]
# is zero. Thus, while there are many terms in the sum, it works out.
jump <- parApply ( cl = clust, X = P[ , , t ], MARGIN = 1,
FUN = fishJumps, sigmaD = sigmaD, sigmaT = sigmaT,
meanD = meanD, bathy = bathy, potSource = potPoint )
jump <- t ( jump )
P [ , , t + 1 ] <- P [ , , t + 1 ] + jump + P [ , , t ]
}
# stop Cluster
stopCluster ( cl = clust )
# Return fish paths
return ( P )
}
# Function to choose next location for fishing, constraints will be based
# on current boat status and whether or not it is trawling or moving. The
# function relies on recursion to make sure new locations are within
# constraints on fishing areas.
# Args: status = fishing or docked
# lat = latitude of current position
# long = longitude of current position
# towing = boolean for selecting movement speed distribution
# eTime = amount of time movement is happening for
# bathy = bathymetry data as produced by bathymetry.R
# Rets: newLoc = a vector of latitude and longitude
boatMove <- function ( status = docked, lat = 0, long = 0, towing = FALSE,
eTime = 1, bathy = bathyTop, histData = histData,
recursive = FALSE )
{
# Recover historic data from entry list.
minDepth <- histData $ minDepth
maxDepth <- histData $ maxDepth
# First, if boat is docked, generate a random starting location
if ( status == docked | ( lat == 0 & long == 0) )
{
# Uniform random draw from the fishing area - very crudely drawn from
# within a polygon around the 8 stat areas
# Choose new latitude
newLat <- runif ( n = 1, min = - 134, max = - 124 )
# Choose new longitude within polygon
yUB <- ( - 6 * newLat - 407 ) / 7
yLB <- -2. * ( newLat + 125 ) / 3. + 47
newLong <- runif ( n = 1, min = yLB, max = yUB )
} else {
# Draw a random direction
tJump <- rnorm ( n = 1, mean = 0, sd = pi / 2 )
# Draw a random motoring speed in knots
{
if ( towing ) speed <- rlnorm ( n = 1, mean = log ( 3 ), sd = 0.3 )
else speed <- rlnorm ( n = 1, mean = log ( 6 ), sd = 0.5 )
}
# Convert speed to degrees per hour
degSpeed <- speed * 1.852 / 111
# Create jump distance
rJump <- (eTime - 1) * degSpeed
# Convert old location to a complex number for adding jump
oldLoc <- complex ( real = lat, imaginary = long )
# Convert jump to complex number
jump <- complex ( modulus = rJump, argument = tJump )
# Make new location
newLoc <- oldLoc + jump
# Recover new latitude and longitude
newLat <- Re ( newLoc )
newLong <- Im ( newLoc )
}
# Look up depth of new location in bathymetry table. First get gridref
gridCell <- bathyLookup ( lat = newLat, long = newLong, bathy = bathy )
xEntry <- gridCell [ 1 ]
yEntry <- gridCell [ 2 ]
# Recover depth from bathy matrix
depth <- bathy $ z [ xEntry, yEntry ]
# Combine new position into a vector for returning
outVec <- c ( newLat, newLong )
if ( recursive )
{
# Recurse function to correct for bad points
while ( depth < minDepth |
depth > maxDepth |
outVec [ 2 ] > 55. |
outVec [ 1 ] > -125. |
outVec [ 2 ] > ( - 6. * outVec [ 1 ] - 407.) / 7. |
outVec [ 2 ] < -2. * ( outVec [ 1 ] + 125 ) / 3. + 47. )
{
# Generate a new location
outVec <- boatMove ( status = status, lat = lat, long = long,
towing = towing, eTime = eTime, bathy = bathy,
histData = histData, recursive = FALSE )
# Look up depth of new location in bathymetry table. First get gridref
gridCell <- bathyLookup ( lat = outVec [ 1 ], long = outVec [ 2 ],
bathy = bathy )
xEntry <- gridCell [ 1 ]
yEntry <- gridCell [ 2 ]
# Recover depth from bathy matrix
depth <- bathy $ z [ xEntry, yEntry ]
}
}
# Return location
return ( outVec )
}
# The following function is the event scheduler, which will take the event number
# and current state of the system and schedule the next event.
# Arguments: time = current time
# event = current event number
# state = slice of B for boat in question
# fel = future event list for the boat in question
#
# Returns: fel = future event list with new event scheduled
eventSched <- function ( time = t, event = eCount,
fel = FEL, ntows = nTows, histData = histData )
{
# Recover boat number, trip threshold and boat number from arguments
boat <- fel [ event, ] $ boat.number
thresh <- fel [ event, ] $ trip.thresh
interFish <- histData $ interFish
meanEventTime <- histData $ meanEventTime
layOver <- histData $ layOver
meanTows <- histData $ meanTows
if ( time != fel [ event, ] $ time.stamp )
{
cat ( "ACK! Failure on time variable - review logic. \n
boat = ", boat, "\n
t = ", time, "\n
time.stamp = ", fel [ event, ] $ time.stamp ); return ( fel )
}
# If boat is docked, set next fishing event
if ( fel [ event, ] $ event.type == docked )
{
# Draw layover time from Poisson distribution
tLay <- fel [ event, ] $ event.time
# Set next time
tNext <- min ( nT, time + tLay )
# Create new threshold for nTows, reset nTows
tripThresh <- rpois ( n = 1, lambda = meanTows )
ntows <- 0
# Create towDuration for next event
towTime <- towDuration ( lam = meanEventTime )
# Add event to FEL
fel [ event + 1, ] <- c ( boat, tNext, fishing, towTime, ntows, tripThresh )
}
# If boat is fishing, check threshold variable, if below threshold then
# set new fishing event, else set docking event.
if ( fel [ event, ] $ event.type == fishing )
{
# recover tow duration for next event time
towDur <- fel [ event, ] $ event.time
# Set next event time by adding towDuration
# to current time
tNext <- time + towDur - 1
# If tripLength >= thresh, dock, else fish again
if ( ntows >= thresh )
{
# Generate layover time
tLay <- layTime ( lam = layOver )
# Add to FEL
fel [ event + 1, ] <- c ( boat, tNext, docked, tLay, 0, 0 )
} else {
# Generate interfishing time
interfishTime <- rpois ( n = 1, lambda = interFish )
# Add to next event time
tNext <- tNext + interfishTime
# Generate set duration for next event
towDurNext <- towDuration ( lam = meanEventTime )
# Add next event to FEL and
# Correct for going over time - dock if basically at the end of the year
if ( tNext + towDurNext > nT )
{
# Set tNext to time limit
tNext <- nT
# update FEL to reflect end of year behaviour
fel [ event + 1, ] <- c ( boat, tNext, docked, 0, 0, 0 )
} else {
fel [ event + 1, ] <- c ( boat, tNext, fishing, towDurNext, ntows + 1,
thresh )
}
}
}
# return appended future event list
return ( fel )
}
# The following function processes discrete events according to the future
# event list (FEL) for each boat and updates the state variables to reflect
# the behaviour of the boat.
# Arguments: event = the counting index of the FEL entry being processed
# fel = the future event list
# state = the slice of the state variable array being updated
#
# Returns: state = the updated slice of the systems state array
eventProc <- function ( event = eCount, fel = FEL, nowlat = nowLat,
nowlong = nowLong, ntows = nTows, histData = histData,
b = B )
{
# Get time stamp from FEL for logic check
time <- fel [ event, ] $ time.stamp
if ( time != fel [ event, ] $ time.stamp )
{
cat ( "ACK! Failure on time variable - review logic. \n
boat = ", boat, "\n
t = ", t, "\n" ); return ( fel )
}
# Recover other parameters for system state
eTime <- fel [ event, ] $ event.time
boat <- fel [ event, ] $ boat.number
status <- fel [ event, ] $ event.type
# Check event type and update state
# First, if the boat is docked
if ( fel [ event, ] $ event.type == docked )
{
# Update state: change status to docked, reset tripLength counter and set
# location to zero
state <- 0 # auto recycles to set state back to docked
}
# Next if the boat is fishing
if ( fel [ event, ] $ event.type == fishing )
{
# generate event starting location
startLoc <- boatMove ( status = status, lat = nowlat, long = nowlong,
towing = FALSE, eTime = interfishTime,
bathy = bathyTop, histData = histData,
recursive = TRUE )
# generate event ending location
endLoc <- boatMove ( status = status, lat = startLoc [ 1 ],
long = startLoc [ 2 ],
towing = TRUE, eTime = eTime, bathy = bathyTop,
histData = histData, recursive = TRUE )
# generate jump sizes
if ( eTime == 1 ) jumps <- 0
else jumps <- ( endLoc - startLoc ) / ( eTime - 1 )
# Recover system state
state <- b [ , time:( time + eTime - 1 ) ]
# Fix this for small tows - not pretty
if ( class ( state ) != "matrix" )
{
state <- as.matrix ( state )
}
# Set location - this should be made more sophisticated in future, even
# use a Markovian approach (for tripLength > 1)
for ( tStep in 0:( eTime - 1 ) )
{
state [ 1:2, tStep + 1 ] <- startLoc + tStep * jumps
}
# Set status to fishing
state [ 3, ] <- fishing
# Increment nTows and update
state [ 4, ] <- ntows
# Store ending location for next event
nowLat <<- endLoc [ 1 ]
nowLong <<- endLoc [ 2 ]
}
# Return state of boat during fishing event
return ( state )
}
# The following function will process an event from the FEL, computing the
# distance between the boat in the event and all fish at that time.
# Arguments: event = a row of the FEL
# B = the array of states for each boat
# F = the array of states for each fish
#
# Returns: dist = a vector of length nF which contains the distances
boatFishDist <- function ( event = FEL [ 1, ], b = B, f = F )
{
# Recover timestamp and event number
time <- event [ 2 ]
boat <- event [ 1 ]
# Get location of boat at time from state array
loc <- b [ boat, 1, time ]
# Compare location of boat for each fish
dist <- f [ ,1 , time ] - loc
# Return a vector of distances
return ( dist )
}
# Function to look up bathymetric grid references for a given point.
# Args: lat = latitude of point
# long = longitude of point
# bathy = list of bathymetric data, produced by bathymetry.R
#
# Rets: out = 2-ple of grid cell references for given point
bathyLookup <- function ( lat = 0, long = 0, bathy = bathyTop )
{
# Extract vectors of grid line refs and matrix of bathymetry
xVec <- bathy $ x
yVec <- bathy $ y
# Now compare Xt and Yt to the vectors of grid lines refs
xDiff <- xVec - lat
yDiff <- yVec - long
# Find minimum difference
xMin <- min ( abs ( xDiff ) )
yMin <- min ( abs ( yDiff ) )
# And which entry has that diff - if there are two equidistant
# then it takes the maximum index. Unsophisticated, but it works.
# In future, perhaps we can shift the finite difference.
xEntry <- max ( which ( abs ( xDiff ) == xMin ) )
yEntry <- max ( which ( abs ( yDiff ) == yMin ) )
# concatenate the grid cell entries and return
out <- c ( xEntry, yEntry )
return ( out )
}
# The following function takes a current location and produces a fish move
# based on habitat (depth) preference and some process error.
# Arguments: Xt = latitude of current position
# Yt = longitude of current position
# sigma = variance of process error
# wgt = multiplicative weight parameter for gradient potential
# bathy = list of bathymetry data as produced by makeTopography
# function in PBS mapping
# Returns: delta = vector of jumps in lat/long
fishJumps <- function ( oldPos = c ( 0, 0 ), sigmaT = pi/3, meanD = 0.01,
sigmaD = 0.004, bathy = bathyGrad, potSource = potPoint )
{
# Source parallel functions
source ( "parFunctions.R" )
# Extract locations from vector
Xt <- oldPos [ 1 ]
Yt <- oldPos [ 2 ]
# If fish has not yet been released, just pass through
if ( Xt == 0 | Yt == 0 )
{
delta <- oldPos
} else {
# Lookup grid cell reference
gridCell <- bathyLookup ( lat = Xt, long = Yt, bathy = bathy )
xEntry <- gridCell [ 1 ]
yEntry <- gridCell [ 2 ]
# Now we want to take finite differences for each coordinate, which we
# look up in a table in bathyGrad
dX <- bathy $ dX [ xEntry, yEntry ]
dY <- bathy $ dY [ xEntry, yEntry ]
# Now we want to fund the compass heading that this represents, use
# previously defined cart2pol function, which returns an ordered
# pair (dist,heading)
muTheta <- cart2pol ( x = -dX, y = -dY ) [ 2 ]
# Get random jumps - fish might be able to swim in reverse, but that's
# okay, it will simulate fish getting spooked or something - fix later
# when you have time to think about what sigma is in a logN dist
Theta <- rnorm ( n = 1, mean = muTheta, sd = sigmaT )
Dist <- rnorm ( n = 1, mean = meanD, sd = sigmaD )
# Now convert back to cartesian coordinates
delta <- pol2cart ( r = Dist, t = Theta )
# If still in inlet, add a potential to overcome depth preference
# Border across which potential function turns off
# y = -6/7 * x - 405/7
if ( Yt >= -6/7 * Xt - 409 / 7 )
{
# Create complex numbers out of current location and the potential
# location
oldPointCplx <- complex ( real = Xt, imaginary = Yt )
potPointCplx <- complex ( real = potSource [ 1 ],
imaginary = potSource [ 2 ] )
# Take the difference of the complex numbers for the direction
potentialCplx <- potPointCplx - oldPointCplx
# The argument of the complex difference is the heading we want
potTheta <- Arg ( potentialCplx )
# Add a jump in that direction to delta
delta <- delta + pol2cart ( r = Dist, t = potTheta )
}
}
# return the new position
return ( delta )
}
# Function to randomly produce a tow duration for each fishing event
# Args: lam = parameter for Poisson distribution drawn from
# Rets: towTime = duration of trawl event
towDuration <- function ( lam = 3 )
{
towTime <- 0
while ( towTime == 0 )
{
towTime <- rpois ( n = 1, lambda = lam)
}
return ( towTime )
}
# Function to randomly produce layover times for fishing vessels
# Args: lam = parameter for Poisson distribution drawn from
# Rets: lay = duration of layover
layTime <- function ( lam = layOver )
{
lay <- rpois ( n = 1, lambda = lam )
return ( lay )
}
# Function for pulling out the first element of a list vector entry -
# to be lapplied below
# Arguments: listVec = a list vector containing lists with multiple entries
# entry = index of listVec from which to recover element
# element = the element number of the list entry to be recovered
#
# Returns out = the element being recovered
listElement <- function ( entry = 1, listVec, element = 1 )
{
# Get element and return
out <- listVec [[ entry ]] [[ element ]]
return ( out )
}
boatDEVS <- function ( boat = 1, histData = histList, T = nT )
{
# Source functions needed in parallel running
source ( "parFunctions.R" )
# Set recursion limit deeper
options ( expressions = 500000 )
# Recover historic data from entry list.
layOver <- histData $ layOver
meanEventTime <- histData $ meanEventTime
meanTows <- histData $ meanTows
tHist <- histData $ tHist
# Create 2D array to hold states for each boat
# First, names for dimensions
Bnames <- list ( )
Bnames [[ 1 ]] <- c ( "latitude", "longitude", "status", "tripLength" )
Bnames [[ 2 ]] <- 1:T
# Then make the array to hold boat state variables
B <- array ( 0, dim = c ( 4, T ), dimnames = Bnames )
# Initialise clock
t <- 0
# Initialise lat, long, interFishTime and tripThresh
nowLat <- 0
nowLong <- 0
interfishTime <- 0
tripThresh <- rpois ( n = 1, lambda = meanTows )
# Future Event List (FEL) is a data frame that contains
# a boat identifier and the time stamp and type of the event
FEL <- data.frame ( boat.number = integer ( length = 0 ),
time.stamp = integer ( length = 0 ),
event.type = integer ( length = 0 ),
event.time = integer ( length = 0 ),
trip.length = integer ( length = 0 ),
trip.thresh = integer ( length = 0 ) )
# 3a. Create first event, add to FEL
# Generate a timestamp - make Poisson so it happens realistically early
tFirst <- runif ( n = 1, min = 1, max = min ( T, 500 ) )
# First event type
eFirst <- fishing
# Generate first towTime (event time variable named eTime)
eTimeFirst <- towDuration ( lam = meanEventTime )
# counter variable for event number
eCount <- 1
# set first tow counter to 1
nTows <- 1
# Add event to FEL - this will be the first fishing event
FEL [ eCount, ] <- c ( boat, tFirst, eFirst, eTimeFirst, nTows, tripThresh )
# 4. loop for DEVS:
# while (t < nT) do {
while ( t < T )
{
# Forward clock to next event
t <- FEL [ eCount , ] $ time.stamp
eTime <- FEL [ eCount, ] $ event.time
nTows <- FEL [ eCount, ] $ trip.length
if ( t + eTime - 1 > T ) { break }
# Process next event on FEL and update boat state
B [
, t:min ( T, t + eTime - 1 )
] <- eventProc (
event = eCount,
fel = FEL,
nowlat = nowLat,
nowlong = nowLong,
ntows = nTows,
histData = histData,
b = B
)
# Schedule a future event, based on the current event
FEL <- eventSched ( time = t, event = eCount,
fel = FEL, ntows = nTows,
histData = histData )
# 4d. increase event counter
eCount <- eCount + 1
# goto 4
}
# Combine boat states and FEL into a list for returning
outList <- list ()
outList $ state <- B
outList $ FEL <- FEL
# return outList
return ( outList )
}
# Function to run a discrete event simulation given some historic
# fishing data on trip length, event duration etc. Essentially
# a wrapper for the function boatDEVS
# Args: dt = a line of a data.table of yeardata, as produced by
# histAnalysis.R
# Rets: out = a list containing a system state array and a FEL
yearDEVS <- function ( dt = FishByYear [ 1, ], T = nT, tHist = trawlHist )
{
# Recover fishing year
year <- dt $ year
# Split up fishing year
years <- str_split ( string = year, pattern = "/" )
year <- as.integer ( years [[ 1 ]] [ 2 ] )
# Reduce tHist to relevant years
tHist <- tHist [ StartYear == year ]
# Recover vector of vessel IDs
boatIDs <- unique ( tHist [ , VESSEL_ID ] )
# Recover number of boats
nB <- length ( boatIDs )
# recover historic averages to pass to the DEVS function
histList <- list ( )
histList $ layOver <- round ( 24 * dt [ , aveLayoverDays ] )