-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdatetimefunc.R
1551 lines (1428 loc) · 52.9 KB
/
datetimefunc.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
# datetimefunc.R
local({
tmp_require_package_namespace <- function(...) {
packages <- as.character(match.call(expand.dots = FALSE)[[2]])
for (p in packages) if (!requireNamespace(p)) install.packages(p)
}
tmp_require_package_library <- function(...) {
packages <- as.character(match.call(expand.dots = FALSE)[[2]])
for (p in packages) {
if (!requireNamespace(p)) {
install.packages(p)
}
library(p, character.only = TRUE)
}
}
tmp_require_package_namespace(
data.table,
dplyr,
ggplot2,
lubridate,
patchwork
)
tmp_require_package_library(
tidyverse
)
})
# =============================================================================
# Namespace-like method: http://stackoverflow.com/questions/1266279/#1319786
# =============================================================================
datetimefunc <- new.env()
# =============================================================================
# Calculate age
# =============================================================================
datetimefunc$calendar_age_lubridate_1 <- function(dob, now) {
# Works with POSIXct or Date values
# http://stackoverflow.com/questions/32312925/time-difference-in-years-with-lubridate
interval_period <- lubridate::interval(dob, now)
full_years <- interval_period %/% lubridate::years(1)
# remaining_weeks <- (
# interval_period %% lubridate::years(1) %/% lubridate::weeks(1)
# )
# remaining_days <- (
# interval_period
# %% lubridate::years(1)
# %% lubridate::weeks(1)
# %/% lubridate::days(1)
# )
return(full_years)
}
datetimefunc$calendarAge <- datetimefunc$calendar_age_lubridate_1
datetimefunc$calendar_age <- function(dob, now)
{
# THIS IS BETTER.
# https://stackoverflow.com/questions/31126726
# https://stackoverflow.com/questions/3611314/calculate-ages-in-r
from_lt <- as.POSIXlt(dob)
to_lt <- as.POSIXlt(now)
age <- to_lt$year - from_lt$year
return(ifelse(
to_lt$mon < from_lt$mon |
(to_lt$mon == from_lt$mon & to_lt$mday < from_lt$mday),
age - 1,
age
))
}
datetimefunc$age_float_years <- function(dob, now, days_per_year = 365.25)
{
days <- as.numeric(difftime(now, dob, units = "days"))
return(days / days_per_year)
}
# =============================================================================
# Durations
# =============================================================================
datetimefunc$duration_units <- function(start_date, end_date, units) {
# https://rawgit.com/rstudio/cheatsheets/main/lubridate.pdf
# "Divide an interval by a duration to determine its physical length."
(
lubridate::interval(start = start_date, end = end_date) /
lubridate::duration(1, units = units)
)
}
datetimefunc$duration_years <- function(start_date, end_date) {
datetimefunc$duration_units(start_date, end_date, units = "years")
}
datetimefunc$duration_days <- function(start_date, end_date) {
datetimefunc$duration_units(start_date, end_date, units = "days")
}
# =============================================================================
# Event time calculations: pulsetable
# =============================================================================
# Functions relating to sequences of times representing "pulsed" events of a
# certain duration. These operate by creating an intermediate object that we'll
# call a "pulsetable" object (actually a list, one of whose elements is a
# table), which is then queried.
#
# Original purpose: renal function analysis, including e.g. "currently on
# lithium", "cumulative time on lithium", "time off lithium since starting".
#
# - Note that pmin(), pmax() mangle durations (e.g. values in days are treated
# as seconds), so convert values to numeric first and back-convert
# afterwards. Or, better, have dimensionless versions and then surround them
# with date-specific versions.
#
# - Note also: base::ifelse() coerces everything to the same type.
# dplyr::if_else() respects type better (but may complain about incompatible
# types!).
#
# - Splitting time: one option is
# indexes <- findInterval(time_now, start_times)
# ... Defaults are correct; see ?findInterval and its first example:
# rightmost.closed = FALSE
# all.inside = FALSE
# left.open = FALSE
# If the "time_now" values are GREATER THAN OR EQUAL TO the test values, they
# get assigned the index of the (greatest such) test value.
#
# I'm not sure what's most elegant after that, though. The problem is that
# the expression start_times[indexes] cannot be used, because indexes
# contains 0 values (an invalid index) -- and the output vector in that
# circumstance is of a DIFFERENT LENGTH and therefore garbled. Similar if you
# use NA instead, etc. Core syntax is:
# https://cran.r-project.org/doc/manuals/r-release/R-intro.html#Index-vectors
# So can use dplyr::if_else(indexes == 0, NA, <something...>).
#
# But we have moved to the "pulsetable" format, so this is less an issue.
datetimefunc$mk_pulsetable_dimensionless <- function(
event_times,
event_durations,
include_interval_table = FALSE,
merge_interval_table = FALSE
) {
# Creates a "pulsetable" object, documenting events for a single subject,
# with a presumed duration for each. This object can then be queried, e.g.
# for dates, via query_pulsetable_ever(), query_pulsetable_times(), and
# query_pulsetable_dates().
#
# This version of the function creates a dimensionless pulsetable object.
# See also mk_pulsetable_dates().
#
# Arguments:
#
# event_times
# Numeric times (e.g. ages in years) at which an event (e.g. lithium
# administration) occurred (more specifically, started to occur).
# event_durations
# Numeric time that each event is presumed to have endured for.
# Either a single number, or a vector as long as event_times.
# Consecutive events can "merge". This is not additive; for example,
# if event duration is 10 and events occur at times 20 and 25, then
# this will be treated as an event starting at time 20 and enduring
# until time 35.
# merge_interval_table
# Merge consecutive contiguous events? Only applicable for the
# interval table. (Pulse calculations are unaffected by such a
# merge.)
#
# Returns a list, with elements:
#
# event_times
# As for the input (event_times), but sorted.
# event_durations
# As for the input, but sorted (to match event_times in the output).
# intervals
# If include_interval_table == FALSE, NULL. Otherwise: a data.table,
# containing one time interval per row, collectively covering all
# time from -Inf to +Inf with no gaps. Columns are:
#
# t_start
# Numeric time at which each interval starts.
# t_end
# Numeric time at which each interval ends. The interval is
# represented by [start, end), i.e. inclusive start, exclusive
# end.
# event
# Is the event occurring (TRUE) or not (FALSE) during this
# interval?
# duration
# Interval duration.
# event_duration
# Interval duration if the event is occurring, or 0 if it's not.
# cum_event_dur
# Cumulative duration, to the END of the interval, spent "during"
# events.
# origin_date
# The date from which times are calculated, or NA if this object
# is not using dates.
# time_units
# Units of time (e.g. "years" or NA).
n_event_times <- length(event_times)
n_durations <- length(event_durations)
# Argument checks
stopifnot(all(is.finite(event_times)))
# ... excludes NA values (but 0-length OK)
stopifnot(n_durations == 1 || n_durations == n_event_times)
stopifnot(all(is.finite(event_durations)))
stopifnot(all(event_durations > 0))
if (n_event_times == 0) {
# Return a "non-event" result.
if (include_interval_table) {
intervals <- data.table(
t_start = -Inf,
t_end = Inf,
event = FALSE,
duration = Inf,
event_duration = 0,
cum_event_dur = 0
)
} else {
intervals <- NULL
}
return(list(
event_times = event_times,
event_durations = event_durations,
intervals = intervals,
origin_date = lubridate::NA_Date_,
time_units = NA_character_
))
}
# From here on, we have at least one event.
# Create a table so that we can sort start times and durations in sync.
intervals_occurring <- data.table::data.table(
t_start = event_times,
src_duration = event_durations
)
data.table::setkeyv(intervals_occurring, c("t_start", "src_duration"))
# Fish out the sorted values, which we'll return.
event_times <- intervals_occurring$t_start
event_durations <- intervals_occurring$src_duration
# Create intervals
# (a) "Event occurring" intervals
if (include_interval_table) {
# We know there is at least one event, as above.
# If there's only one event, though, we need to do very little.
n_events <- length(event_times)
if (n_events == 1) {
intervals_occurring[, t_end := t_start + src_duration]
} else {
# More than one event.
intervals_occurring[
,
t_end := pmin(
# When this event expires:
t_start + src_duration,
# When the next event starts:
c(event_times[2 : n_events], Inf)
)
# ... up until the expiry of this event, or until the next
# event starts
]
# (b) Merge consecutive contiguous events, if required.
# Only applicable if more than one event.
if (merge_interval_table) {
# Already sorted by t_start then src_duration, as above.
intervals_occurring[
,
prev_event_ends := c(-Inf, t_end[1 : (n_events - 1)])
]
intervals_occurring[
,
groupnum := cumsum(
ifelse(t_start > prev_event_ends, 1, 0)
# ... 1 if we're starting a new group, 0 otherwise.
)
]
intervals_occurring <- intervals_occurring[
,
.(
t_start = min(t_start),
t_end = max(t_end)
),
by = groupnum
]
intervals_occurring[, groupnum := NULL]
intervals_occurring[, prev_event_ends := NULL]
}
}
intervals_occurring[, event := TRUE]
intervals_occurring[, src_duration := NULL]
# (c) Now add in "non-occurring" events: the gaps.
# Any overlapping intervals will be culled later.
intervals_not_occurring <- data.table::data.table(
t_start = c(-Inf, intervals_occurring$t_end),
t_end = c(intervals_occurring$t_start, Inf),
event = FALSE
)
# (d) Combine and finish off calculations.
intervals <- rbind(intervals_occurring, intervals_not_occurring)
intervals[, duration := t_end - t_start]
intervals <- intervals[duration > 0]
# ... eliminates dummy non-event intervals
data.table::setkeyv(intervals, c("t_start", "duration"))
intervals[, event_duration := ifelse(event, duration, 0)]
# ... don't multiply; duration may be infinite
intervals[, cum_event_dur := cumsum(event_duration)]
} else {
intervals <- NULL
}
return(list(
event_times = event_times,
event_durations = event_durations,
intervals = intervals,
origin_date = lubridate::NA_Date_,
time_units = NA_character_
))
}
datetimefunc$mk_pulsetable_dates <- function(
origin_date,
event_dates,
event_durations,
time_units = "years",
include_interval_table = FALSE
) {
# As for mk_pulsetable_dimensionless(), which it relies on, but using
# dates.
#
# Arguments:
#
# origin_date
# A date before all others, used as the reference date. Typically the
# DOB for a patient, making "times" equivalent to "ages".
# event_dates
# Should be of type as.Date().
# event_durations
# Should be a lubridate duration in a sensible (constant) unit, e.g.
# lubridate::duration(30, units = "days") -- or a vector of these, of
# the same length as event_dates. Though lubridate does use
# constants, e.g. 365.25 days per year for "years" (see
# ?lubridate::duration), so "years" is fine.
# time_units
# Textual units (e.g. "days", "years") to operate with internally.
# As used by the lubridate package.
# include_interval_table
# As for mk_pulsetable_dimensionless().
#
# Returns:
#
# As for mk_pulsetable_dimensionless(). However, if
# include_interval_table == TRUE, the following columns are also added to
# the "intervals" element:
#
# t_start_date
# Date version of t_start.
# t_end_date
# Date version of t_end.
if (!(length(origin_date) == 1
&& lubridate::is.Date(origin_date))) {
stop("Bad origin_date parameter: ", origin_date)
}
n_event_dates <- length(event_dates)
if (!(n_event_dates == 0 || all(lubridate::is.Date(event_dates)))) {
stop("Bad event_dates parameter: ", event_dates)
}
n_event_durations <- length(event_durations)
if (!(
(n_event_durations == 1 || n_event_durations == n_event_dates)
&& all(lubridate::is.duration(event_durations))
)) {
stop("Bad event_durations parameter: ", event_durations)
}
pt <- datetimefunc$mk_pulsetable_dimensionless(
event_times = datetimefunc$duration_units(
start_date = origin_date,
end_date = event_dates,
units = time_units
),
event_durations = (
event_durations /
lubridate::duration(1, units = time_units)
),
include_interval_table = include_interval_table
)
if (include_interval_table) {
pt$intervals[, t_start_date := as.Date(
origin_date + lubridate::duration(t_start, units = time_units)
)]
pt$intervals[, t_end_date := as.Date(
origin_date + lubridate::duration(t_end, units = time_units)
)]
# A date plus "1 day" gives a date, but a date plus "1 year" gives a
# datetime, so we'll force to a date.
}
pt$origin_date <- origin_date
pt$time_units <- time_units
return(pt)
}
datetimefunc$query_pulsetable_ever <- function(pt) {
# Queries a pulsetable in a very basic way: "Did the event ever occur?"
# Don't rely on the existence of pt$intervals; that is only non-NULL if
# include_interval_table was set during pulsetable creation.
return(length(pt$event_times) > 0)
}
datetimefunc$query_pulsetable_times <- function(pulsetable, query_times) {
# Query a pulse table (see above -- relating to a single subject) at
# various times (in the dimensionless time units used within the
# pulsetable).
#
# This version operates in parallel and is sufficiently fast. It uses only
# the very plain data from mk_pulsetable_dimensionless(), i.e. the
# event_times and event_durations; it doesn't use the interval table.
#
# Arguments:
#
# pulsetable
# The pulse table object (list, as above) to query.
# query_times
# The (dimensionless) times at which to produce a row in the output.
#
# Returns a data.table with columns:
#
# t
# The input times, i.e. query_times.
# current
# Is the event occurring at this time? (Boolean.)
# hx
# Has the event happened at/before time t? (Boolean.)
# t_since_first
# Time since the first occurrence (0 if before or has never
# occurred).
# cum_t_on
# Cumulative time that the subject has been exposed to the event, at
# time t.
# cum_t_after
# Cumulative time that the subject has had OFF exposure, after the
# first exposure. (Will be t_since_first - cum_t_on.)
# t_since_last
# Time since the last known exposure.
# ever
# Does the event ever occur for the subject (across the lifetime,
# including in the future)? Boolean. Obviously, this value will be
# the same for all values of t.
stopifnot(all(is.numeric(query_times)))
# ... prevents NA values; also fails for empty input
event_times <- pulsetable$event_times # sorted, but may be empty
event_durations <- pulsetable$event_durations
# ... a single number or a vector matching event_times
n_events <- length(event_times)
n_durations <- length(event_durations)
ever <- n_events > 0
if (ever) {
# ---------------------------------------------------------------------
# current
# ---------------------------------------------------------------------
# - https://stackoverflow.com/questions/60584096/how-to-check-if-pairs-from-df2-are-in-pairs-of-df1-inclusive-in-r
# - https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/findInterval
# - findInterval() requires ascending (non-decreasing) values in its
# second argument.
# - use dplyr::if_else() rather than base::ifelse() if types are a
# concern, because dplyr::if_else() preserves type.
indexes_danger <- findInterval(query_times, event_times)
# ... Defaults are correct; see ?findInterval and its first example:
# rightmost.closed = FALSE
# all.inside = FALSE
# left.open = FALSE
# - If the "x" values are GREATER THAN OR EQUAL TO the test values
# ("vec"), they get assigned the index of the (greatest such) test
# value. If an "x" value is SMALLER THAN ALL the test values, the
# output is 0. (And that creates an indexing danger, as below.)
# - The second argument must be non-decreasing and not contain NAs,
# but findInterval() checks that itself.
# In what follows, beware the following. The expression
# event_times[indexes_danger] cannot be used, because indexes_danger
# contains 0 values (an invalid index) -- and the output vector in that
# circumstance is of a DIFFERENT LENGTH and therefore garbled. Similar
# if you use NA instead, etc. Core syntax is:
# https://cran.r-project.org/doc/manuals/r-release/R-intro.html#Index-vectors
# Therefore, we must create indexes_safer, but only use its lookup
# values when indexes_danger != 0.
invalid_indexes <- indexes_danger == 0
indexes_safer <- ifelse(invalid_indexes, 1, indexes_danger)
relevant_starts <- event_times[indexes_safer]
if (n_durations > 1) {
relevant_durations <- event_durations[indexes_safer]
} else {
relevant_durations <- event_durations # single number
}
current <- ifelse(
invalid_indexes, # query time before first start time?
FALSE, # if so, then definitely not current
query_times < relevant_starts + relevant_durations
# We use "up to (not including) the end time".
)
# ---------------------------------------------------------------------
# hx (history)
# ---------------------------------------------------------------------
# Could use:
# first_event <- min(event_times)
# but we can instead rely on mk_pulsetable_dimensionless() sorting its
# event times, and use:
first_event <- event_times[1]
hx <- query_times >= first_event
# ---------------------------------------------------------------------
# t_since_first
# ---------------------------------------------------------------------
t_since_first <- pmax(0, query_times - first_event)
# ---------------------------------------------------------------------
# cum_t_on, cum_t_after, t_since_last
# ---------------------------------------------------------------------
if (n_events >= 2) {
event_ends <- pmin( # until the first of:
event_times + event_durations, # this event ends...
c(event_times[2 : n_events], Inf) # ... or the next one starts
)
event_durations <- event_ends - event_times
cum_durations <- cumsum(event_durations) # at the end of events
cum_duration_at_start <- c(0, cum_durations[1 : n_events - 1])
last_exposure <- max(event_ends)
} else {
# n_events is 1
cum_duration_at_start <- 0
last_exposure <- event_times + event_durations
}
cum_t_on <- ifelse(
invalid_indexes, # is the query time before the first start time?
0,
(
# Cumulative time at the start of the latest relevant event
cum_duration_at_start[indexes_safer]
+
# Applicable time since the start of the latest relevant event
pmin(
query_times - relevant_starts,
relevant_durations
)
)
)
cum_t_after <- t_since_first - cum_t_on
t_since_last <- pmax(0, query_times - last_exposure)
# cat("- query_pulsetable_times():\n")
# cat("... query_times:\n"); print(query_times)
# cat("... event_times:\n"); print(event_times)
# cat("... event_durations:\n"); print(event_durations)
# cat("... indexes_danger:\n"); print(indexes_danger)
# cat("... invalid_indexes:\n"); print(invalid_indexes)
# cat("... indexes_safer:\n"); print(indexes_safer)
# cat("... current:\n"); print(current)
# cat("... event_durations:\n"); print(event_durations)
# cat("... cum_durations:\n"); print(cum_durations)
# cat("... cum_duration_at_start:\n"); print(cum_duration_at_start)
# cat("... cum_t_on:\n"); print(cum_t_on)
# cat("... t_since_last:\n"); print(t_since_last)
} else {
# never!
current <- FALSE
hx <- FALSE
t_since_first <- 0
cum_t_on <- 0
cum_t_after <- 0
t_since_last <- 0
}
return(data.table(
t = query_times,
current = current,
hx = hx,
t_since_first = t_since_first,
cum_t_on = cum_t_on,
cum_t_after = cum_t_after,
t_since_last = t_since_last,
ever = ever
))
}
datetimefunc$query_pulsetable_times_slow <- function(pulsetable, query_times) {
# See query_pulsetable_times() above. This version is TOO SLOW: e.g. 19.3
# seconds for 1000 interations with p1/p1_test_times in the test function.
# It uses the interval table.
stopifnot(all(is.numeric(query_times))) # also fails for empty input
intervals <- pulsetable$intervals
if (is.null(intervals)) {
stop(paste0(
"Must use create_interval_table = TRUE argument to ",
"mk_pulsetable_dimensionless() or mk_pulsetable_dates() to use ",
"this version of the function."
))
}
ever <- any(intervals$event)
last_exposure <- ifelse(
ever,
max(intervals %>% filter(event == TRUE) %>% pull(t_end)),
NA_real_
)
query_fn <- function(t) { # t is a SINGLE VALUE, the query time.
# Slices
previous_and_current_intervals <- (
# "finishes before t [= previous], or starts before/at t and not
# yet finished [= current]"
intervals
%>% filter(t_end <= t | (t_start <= t & t < t_end))
# ... remembering that t_end is exclusive, not inclusive.
)
current_interval <- (
previous_and_current_intervals
%>% slice_tail(n = 1)
)
first_prev_current_with_event <- (
previous_and_current_intervals
%>% filter(event == TRUE)
%>% slice_head(n = 1)
)
# Booleans
hx <- nrow(first_prev_current_with_event) > 0
current <- current_interval$event
# Debugging
# cat("--- t =", t, "\n")
# cat("current_interval:\n"); print(current_interval)
# cat("previous_and_current_intervals:\n"); print(previous_and_current_intervals)
# cat("first_prev_current_with_event:\n"); print(first_prev_current_with_event)
# Time calculations
if (hx) {
# t_since_first
t_first <- first_prev_current_with_event$t_start
t_since_first <- t - t_first
# cum_t_on
t_during_this_interval <- t - current_interval$t_start
if (current) {
t_on_during_this_interval <- t_during_this_interval
t_off_during_this_interval <- 0
} else {
t_on_during_this_interval <- 0
t_off_during_this_interval <- t_during_this_interval
}
previous_intervals <- (
previous_and_current_intervals %>% slice_head(n = -1)
)
last_previous_interval <- previous_intervals %>% slice_tail(n = 1)
cum_t_on <- t_on_during_this_interval
if (nrow(last_previous_interval) > 0) {
cum_t_on <- cum_t_on + last_previous_interval$cum_event_dur
}
# cum_t_after
prev_off_intervals_after_first <- (
previous_intervals
%>% filter(t_first <= t_start & !event)
)
cum_t_after <- (
sum(prev_off_intervals_after_first$duration)
+ t_off_during_this_interval
)
t_since_last <- max(0, t - last_exposure)
# debugging:
# cat("previous_intervals:\n"); print(previous_intervals)
# cat("last_previous_interval:\n"); print(last_previous_interval)
# cat("t_first:\n"); print(t_first)
# cat("t_on_during_this_interval:\n"); print(t_on_during_this_interval)
# cat("t_off_during_this_interval:\n"); print(t_off_during_this_interval)
# cat("prev_off_intervals_after_first:\n"); print(prev_off_intervals_after_first)
} else {
t_since_first <- 0
cum_t_on <- 0
cum_t_after <- 0
t_since_last <- 0
}
return(data.table(
t = t,
current = current,
hx = hx,
t_since_first = t_since_first,
cum_t_on = cum_t_on,
cum_t_after = cum_t_after,
t_since_last = t_since_last
))
}
result <- (
tibble(t = query_times)
%>% rowwise()
%>% reframe(query_fn(t))
%>% mutate(ever = ever)
%>% as.data.table()
)
return(result)
}
datetimefunc$query_pulsetable_dates <- function(
pulsetable,
query_dates,
use_slow = FALSE
) {
# Query a pulsetable using dates (not dimensionless times).
#
# Arguments:
#
# pulsetable
# The pulse table to query (using dimensionless times).
# query_dates
# The dates to produce results for, analogous to query_times for
# query_pulsetable_times().
# use_slow
# Use a slow method (for cross-checking). Should NOT be true for
# production code.
#
# Returns:
# As for query_pulsetable_times(), but now the column "t" is a date
# column, and there is an additional column:
#
# t_raw
# The underlying "t" column.
stopifnot(all(lubridate::is.Date(query_dates)))
if (is.na(pulsetable$origin_date) || is.na(pulsetable$time_units)) {
stop(paste0(
"For query_pulsetable_dates(), use a pulsetable created by ",
"mk_pulsetable_dates()"
))
}
query_times <- datetimefunc$duration_units(
start_date = pulsetable$origin_date,
end_date = query_dates,
units = pulsetable$time_units
)
if (use_slow) {
q <- datetimefunc$query_pulsetable_times_slow(
pulsetable = pulsetable,
query_times = query_times
)
} else {
q <- datetimefunc$query_pulsetable_times(
pulsetable = pulsetable,
query_times = query_times
)
}
q[, t_raw := t]
q[, t := query_dates]
return(q)
}
datetimefunc$test_pulsetable <- function(verbose = TRUE) {
# Create and query pulsetable objects.
line <- paste(rep("=", 79), collapse = "")
mktitle <- function(x) {
cat(line, "\n- ", x, "\n", line, "\n", sep = "")
}
# -------------------------------------------------------------------------
# 1
# -------------------------------------------------------------------------
p1a <- datetimefunc$mk_pulsetable_dimensionless(
event_times = c(5, 20, 100, 105, 150, 200),
event_durations = 10,
include_interval_table = TRUE
)
if (verbose) {
mktitle("p1")
print(p1a)
}
# Very basic query:
q1a_ever <- datetimefunc$query_pulsetable_ever(p1a)
if (verbose) {
mktitle("q1a_ever")
print(q1a_ever)
}
p1b <- datetimefunc$mk_pulsetable_dimensionless(
event_times = c(5, 20, 100, 105, 150, 200),
event_durations = 10,
include_interval_table = FALSE
) # same as p1a but without the interval table
q1b_ever <- datetimefunc$query_pulsetable_ever(p1b)
stopifnot(identical(q1a_ever, q1b_ever))
# Times, two ways:
p1_test_times <- c(0, 5, 7, 17, 50, 103, 115, 500)
q1a <- datetimefunc$query_pulsetable_times(p1a, p1_test_times)
q1b <- datetimefunc$query_pulsetable_times_slow(p1a, p1_test_times)
if (verbose) {
mktitle("q1a")
print(q1a)
mktitle("q1b")
print(q1b)
}
stopifnot(isTRUE(all.equal(q1a, q1b)))
# - use all.equal(), not identical(); the latter reports differences that
# are due to infinitesimal floating-point differences; the first doesn't
# care (appropriately).
# - if discrepancy: print(q1a == q1b), then fix bug!
# Speed test
n_tests <- 1000
mktitle("Speed test, query_pulsetable_times")
tmp_start <- Sys.time()
for (i in 1:n_tests) {
datetimefunc$query_pulsetable_times(p1a, p1_test_times)
}
tmp_end <- Sys.time()
cat("- ", n_tests, " iterations took:\n", sep = "")
print(tmp_end - tmp_start)
# 19.3 seconds for query_pulsetable_times_slow (otter)
# ~0.5 seconds for query_pulsetable_times (otter) [or ~1.3s on shrike]
# ... though up to ~1.2 s when fiddling around with conditionality
# cat("Speed test, query_pulsetable_times with few columns (hx only):\n")
# tmp_start <- Sys.time()
# for (i in 1:n_tests) {
# datetimefunc$query_pulsetable_times(
# p1,
# p1_test_times,
# with_current = FALSE,
# with_hx = TRUE,
# with_t_since_first = FALSE,
# with_cum_t_on = FALSE,
# with_cum_t_after = FALSE
# )
# }
# tmp_end <- Sys.time()
# cat("- ", n_tests, " iterations took:\n", sep = "")
# print(tmp_end - tmp_start)
# # ... about 1.14 s (otter); so conditionality on variables NOT helpful.
# -------------------------------------------------------------------------
# 2
# -------------------------------------------------------------------------
p2_origin_date <- as.Date("1900-01-01")
p2_time_units <- "years"
p2 <- datetimefunc$mk_pulsetable_dates(
origin_date = p2_origin_date,
event_dates = as.Date(c(
"1910-01-01", "1915-01-01", "1915-06-01", "1940-01-01"
)),
event_durations = lubridate::duration(300, units = "days"),
time_units = p2_time_units,
include_interval_table = TRUE
)
if (verbose) {
mktitle("p2")
print(p2)
}
# Dates, two ways:
p2_query_dates <- as.Date(c(
"1905-01-01", "1915-01-03", "1915-06-01", "1970-01-01"
))
q2a <- datetimefunc$query_pulsetable_dates(
pulsetable = p2,
query_dates = p2_query_dates
)
q2b <- datetimefunc$query_pulsetable_dates(
pulsetable = p2,
query_dates = p2_query_dates,
use_slow = TRUE
)
if (verbose) {
mktitle("q2a")
print(q2a)
mktitle("q2b")
print(q2b)
}
stopifnot(isTRUE(all.equal(q2a, q2b)))
# -------------------------------------------------------------------------
# 3
# -------------------------------------------------------------------------
# An empty one:
p3 <- datetimefunc$mk_pulsetable_dimensionless(
event_times = c(),
event_durations = 10,
include_interval_table = TRUE
)
if (verbose) {
mktitle("p3")
print(p3)
}
# Empty ones:
q3a <- datetimefunc$query_pulsetable_times(p3, p1_test_times)
q3b <- datetimefunc$query_pulsetable_times_slow(p3, p1_test_times)
if (verbose) {
mktitle("q3a")
print(q3a)
mktitle("q3b")
print(q3b)
}
stopifnot(isTRUE(all.equal(q3a, q3b)))
# -------------------------------------------------------------------------
# 4
# -------------------------------------------------------------------------
# Another empty one:
p4 <- datetimefunc$mk_pulsetable_dates(
origin_date = p2_origin_date,
event_dates = c(),
event_durations = lubridate::duration(300, units = "days"),
time_units = p2_time_units,
include_interval_table = TRUE
)
if (verbose) {
mktitle("p4")
print(p4)
}
# Empty ones:
q4a <- datetimefunc$query_pulsetable_dates(p4, p2_query_dates)
q4b <- datetimefunc$query_pulsetable_dates(p4, p2_query_dates,
use_slow = TRUE)
if (verbose) {
mktitle("q4a")
print(q4a)
mktitle("q4b")
print(q4b)
}
stopifnot(isTRUE(all.equal(q4a, q4b)))
# -------------------------------------------------------------------------
# 5
# -------------------------------------------------------------------------
# A single-event one:
p5 <- datetimefunc$mk_pulsetable_dimensionless(
event_times = c(7),
event_durations = 10,
include_interval_table = TRUE
)
if (verbose) {
mktitle("p5")
print(p5)
}
# Single-event ones:
q5a <- datetimefunc$query_pulsetable_times(p5, p1_test_times)
q5b <- datetimefunc$query_pulsetable_times_slow(p5, p1_test_times)
if (verbose) {
mktitle("q5a")
print(q5a)
mktitle("q5b")
print(q5b)
}
stopifnot(isTRUE(all.equal(q5a, q5b)))
# -------------------------------------------------------------------------
# 6
# -------------------------------------------------------------------------
# Multiple event durations:
p6 <- datetimefunc$mk_pulsetable_dimensionless(
event_times = c(5, 20, 100, 105, 150, 200),
event_durations = c(10, 20, 30, 30, 20, 20),
# checked: it fails with e.g. length 2
include_interval_table = TRUE
)
if (verbose) {
mktitle("p6")
print(p6)