-
Notifications
You must be signed in to change notification settings - Fork 3
/
alignment.jl
1225 lines (1047 loc) · 40.4 KB
/
alignment.jl
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
"""Represent a technique for aligning two timeseries."""
abstract type Alignment end
struct LeftAlignment <: Alignment end
struct UnionAlignment <: Alignment end
struct IntersectAlignment <: Alignment end
"""
LEFT
For inputs `(A, B, ...)`, tick whenever `A` ticks so long as all inputs are active.
"""
const LEFT = LeftAlignment()
"""
UNION
For inputs `(A, B, ...)`, tick whenever any input ticks so long as all inputs are active.
"""
const UNION = UnionAlignment()
"""
INTERSECT
For inputs `(A, B, ...)`, tick whenever all inputs tick simultaneously.
"""
const INTERSECT = IntersectAlignment()
"""The default alignment for operators when not specified."""
const DEFAULT_ALIGNMENT = UNION
"""
UnaryNodeOp{T} <: NodeOp{T}
An abstract type representing a node op with a single parent.
"""
abstract type UnaryNodeOp{T} <: NodeOp{T} end
"""
BinaryNodeOp{T,A<:Alignment} <: NodeOp{T}
An abstract type representing a node op with two parents, and using alignment `A`.
"""
abstract type BinaryNodeOp{T,A<:Alignment} <: NodeOp{T} end
"""
NaryNodeOp{N,T,A<:Alignment} <: NodeOp{T}
An abstract type representing a node op with `N` parents, and using alignment `A`.
This type should be avoided for `N < 3`, since in these cases it would be more appropriate
to use either [`TimeDag.UnaryNodeOp`](@ref) or [`TimeDag.BinaryNodeOp`](@ref).
"""
abstract type NaryNodeOp{N,T,A<:Alignment} <: NodeOp{T} end
# Specialised dispatches for cases where we know about alignment.
# In this case we can also provide optimisations around empty nodes.
function obtain_node(parents::Tuple{Node}, op::UnaryNodeOp{T}) where {T}
_is_empty(@inbounds(only(parents))) && return empty_node(T)
# Call the generic `obtain_node` implementation.
return invoke(obtain_node, Tuple{Tuple{Node},NodeOp}, parents, op)
end
"""
_get_constant_inputs(parents, op)
For use *only* in the specialised `obtain_node`.
It assumes that all `parents` are either constant or empty, and that at least one of
`parents` is empty.
"""
function _get_constant_inputs(parents::Tuple{Node,Node}, op::BinaryNodeOp)
nl, nr = parents
return if _is_constant(nl) # && _is_empty(nr)
(nl, constant(initial_right(op)))
else # _is_empty(nl) && _is_constant(nr)
(constant(initial_left(op)), nr)
end
end
function _get_constant_inputs(parents::NTuple{N,Node}, op::NaryNodeOp{N}) where {N}
#! format: off
return Tuple(
_is_constant(parent) ? parent : constant(initial)
for (initial, parent) in zip(initial_values(op), parents)
)
#! format: on
end
function obtain_node(
parents::NTuple{N,Node}, op::Union{BinaryNodeOp{T,A},NaryNodeOp{M,T,A}}
) where {N,T,M,A<:Alignment}
# If all inputs are empty, the output will definitely be empty.
all(_is_empty, parents) && return empty_node(T)
_is_const_or_empty(n) = _is_constant(n) || _is_empty(n)
if (
any(_is_empty, parents) &&
all(_is_const_or_empty, parents) &&
_can_propagate_constant(op)
)
# Some inputs are empty, and all are either constant or empty.
# The operator supports constant propagation.
# Therefore, the output will definitely either be a constant or empty.
# If we don't have initial values, the output will be empty.
isnothing(initial_values) && return empty_node(T)
# We can propagate constants if all the following are true:
# * `initial_values` are provided
# * alignment is either:
# - UNION
# - LEFT, so long as the first input is a constant (not empty)
return if (
has_initial_values(op) &&
(A == UnionAlignment || (A == LeftAlignment && _is_constant(first(parents))))
)
# Replace empty inputs with intial values and propagate.
constant(T, _propagate_constant_value(op, _get_constant_inputs(parents, op)))
else
# In all other cases here the output will be empty.
empty_node(T)
end
end
# No optimisations can be applied, fall back to generic `obtain_node` implementation.
return invoke(obtain_node, Tuple{NTuple{N,Node},NodeOp}, parents, op)
end
# A note on the design choice here, which is motivated by performance reasons & profiling.
#
# Options considered:
# 1. Return `(value::T, should_tick::Bool)` pair always
# 2. Take `out::Ref{T}` as a parameter, return `should_tick::Bool`
# 3. Return `Maybe{T}`.
#
# Option 1 was disfavoured, because if `should_tick` is false, one still needs to invent a
# `value` of type `T`, which is possibly hard in general.
# Option 2 was found, from benchmarking, to be moderately slower than the other choices.
#
# Option 3 was found to retain the performance of option 1 with minimal overhead.
#
# For cases when we know the node will always tick (as indicated by `always_ticks(op)`) we
# just return a raw `T`, as the extra information will not be used.
"""
operator!(op::UnaryNodeOp{T}, (state,), (time,) x) -> T / Maybe{T}
operator!(op::BinaryNodeOp{T}, (state,), (time,) x, y) -> T / Maybe{T}
operator!(op::NaryNodeOp{N,T}, (state,), (time,) x, y, z...) -> T / Maybe{T}
Perform the operation for this node.
When defining a method of this for a new op, follow these rules:
- `state` should be omitted iff [`TimeDag.stateless_operator`](@ref).
- `time` should be omitted iff [`TimeDag.time_agnostic`](@ref).
- All values `x, y, z...` should be omittted iff [`TimeDag.value_agnostic`](@ref).
For stateful operations, this operator should mutate `state` as required.
The return value `out` should be of type `T` iff [`TimeDag.always_ticks`](@ref) is true,
otherwise it should be of type [`TimeDag.Maybe`](@ref)`{T}`.
If `out <: Maybe{T}`, and has `!valid(out)`, this indicates that we do not wish to emit a
knot at this time, and it will be skipped. Otherwise, `value(out)` will be used as the
output value.
"""
function operator! end
"""
always_ticks(node) -> Bool
always_ticks(op) -> Bool
Returns true iff the return value from `operator!` can be assumed to always be valid.
If `true`, `operator!(::Node{T}, ...)` should return a `T`.
If `false`, `operator!(::Node{T}, ...)` should return a `Maybe{T}`.
Note, that for sensible performance characteristics, this should be knowable from
`typeof(op)`
"""
always_ticks(node::Node) = always_ticks(node.op)
always_ticks(::NodeOp) = false
"""
stateless_operator(node) -> Bool
stateless_operator(op) -> Bool
Returns true iff `operator(op, ...)` would never look at or modify the evaluation state.
If this returns true, `create_operator_evaluation_state` will not be used.
Note that if an `op` has `stateless(op)` returning true, then it necessarily should also
return true here. The default implementation is to return `stateless(op)`, meaning that if
one is creating a node that is fully stateless, one need only define `stateless`.
For optimal performance, this should be knowable from the type of `op` alone.
"""
stateless_operator(node::Node) = stateless_operator(node.op)
stateless_operator(op::NodeOp) = stateless(op)
"""
time_agnostic(node) -> Bool
time_agnostic(op) -> Bool
Returns true iff `op` does not care about the time of the input knot(s).
For optimal performance, this should be knowable from the type of `op` alone.
"""
time_agnostic(node::Node) = time_agnostic(node.op)
time_agnostic(::NodeOp) = false
"""
value_agnostic(node) -> Bool
value_agnostic(op) -> Bool
Returns true iff `op` does not care about the value(s) of the input knot(s).
For optimal performance, this should be knowable from the type of `op` alone.
"""
value_agnostic(node::Node) = value_agnostic(node.op)
value_agnostic(::NodeOp) = false
"""
create_operator_evaluation_state(parents, op::NodeOp) -> NodeEvaluationState
Create an empty evaluation state for the given node, when starting evaluation at the
specified time.
Note that this is state that will be passed to `operator`. The overall node may additionally
wrap this state with further state, if this is necessary for e.g. alignment.
"""
function create_operator_evaluation_state end
"""
has_initial_values(op) -> Bool
If this returns true, it indicates that initial values for the `op`'s parents are specified.
See the documentation on [Initial values](@ref) for further information.
"""
has_initial_values(::BinaryNodeOp) = false
has_initial_values(::NaryNodeOp) = false
"""
initial_left(op::BinaryNodeOp) -> L
Specify the initial value to use for the first parent of the given `op`.
Needs to be defined if [`has_initial_values`](@ref) returns true, and alignment is
[`UNION`](@ref). For other alignments it is not required.
"""
function initial_left end
"""
initial_right(op::BinaryNodeOp) -> R
Specify the initial value to use for the second parent of the given `op`.
Needs to be defined if `has_initial_values(op)` returns true, and alignment is
[`UNION`](@ref) or [`LEFT`](@ref). For [`INTERSECT`](@ref) alignment it is not required.
"""
function initial_right end
"""
initial_values(op::NaryNodeOp) -> Tuple
Specify the initial values to use for all parents of the given `op`.
Needs to be defined for nary ops for which [`has_initial_values`](@ref) returns true.
"""
function initial_values end
"""Convenience method to dispatch to reduced-argument `operator!` calls."""
function _operator!(op::NodeOp, state::NodeEvaluationState, t::DateTime, values...)
return if stateless_operator(op) && time_agnostic(op)
value_agnostic(op) ? operator!(op) : operator!(op, values...)
elseif stateless_operator(op) && !time_agnostic(op)
value_agnostic(op) ? operator!(op, t) : operator!(op, t, values...)
elseif !stateless_operator(op) && time_agnostic(op)
value_agnostic(op) ? operator!(op, state) : operator!(op, state, values...)
elseif !stateless_operator(op) && !time_agnostic(op)
value_agnostic(op) ? operator!(op, state, t) : operator!(op, state, t, values...)
else
error("Error! We should have dispatched to a more specialised method.")
end
end
function _can_propagate_constant(op::Union{UnaryNodeOp,BinaryNodeOp,NaryNodeOp})
return always_ticks(op) && stateless_operator(op) && time_agnostic(op)
end
function _propagate_constant_value(op::UnaryNodeOp, parents::Tuple{Node})
# NB, we know that time & state is ignored (due to _can_propagate_constant).
return operator!(op, value(@inbounds(parents[1])))
end
function _propagate_constant_value(op::BinaryNodeOp, parents::Tuple{Node,Node})
return operator!(op, value(@inbounds(parents[1])), value(@inbounds(parents[2])))
end
function _propagate_constant_value(op::NaryNodeOp{N}, parents::NTuple{N,Node}) where {N}
return operator!(op, map(value, parents)...)
end
"""
_create_operator_evaluation_state(parents, op) -> NodeEvaluationState
Internal function that will look at `stateless_operator`, and iff it is false call
`create_operator_evaluation_state`. Otherwise return an empty node state.
"""
function _create_operator_evaluation_state(parents, op)
return if stateless_operator(op)
EMPTY_NODE_STATE
else
create_operator_evaluation_state(parents, op)
end
end
# An unary node has no alignment state, so any state comes purely from the operator.
function create_evaluation_state(parents::Tuple{Node}, op::UnaryNodeOp)
return _create_operator_evaluation_state(parents, op)
end
function run_node!(
node_op::UnaryNodeOp{T},
state::NodeEvaluationState,
::DateTime, # time_start
::DateTime, # time_end
input::Block{L},
) where {T,L}
n = length(input)
values = _allocate_values(T, n)
return if always_ticks(node_op)
# We can ignore the validity of the return value of the operator, since we have been
# promised that it will always tick. Hence we can use a for loop too.
@inbounds for i in 1:n
time = input.times[i]
values[i] = _operator!(node_op, state, time, input.values[i])
end
Block(unchecked, input.times, values)
else
times = _allocate_times(n)
j = 1
@inbounds for i in 1:n
time = input.times[i]
out = _operator!(node_op, state, time, input.values[i])
if valid(out)
values[j] = unsafe_value(out)
times[j] = input.times[i]
j += 1
end
end
_trim!(times, j - 1)
_trim!(values, j - 1)
Block(unchecked, times, values)
end
end
"""Apply, assuming `input_l` and `input_r` have identical alignment."""
function _apply_fast_align_binary!(
op::BinaryNodeOp{T}, operator_state::NodeEvaluationState, input_l::Block, input_r::Block
) where {T}
n = length(input_l)
values = _allocate_values(T, n)
return if always_ticks(op)
# We shouldn't assume that it is valid to broadcast f over the inputs, so loop
# manually.
@inbounds for i in 1:n
time = input_l.times[i]
values[i] = _operator!(
op, operator_state, time, input_l.values[i], input_r.values[i]
)
end
Block(unchecked, input_l.times, values)
else
# FIXME Implement this branch!
error("Not implemented!")
end
end
abstract type UnionAlignmentState{L,R} <: NodeEvaluationState end
mutable struct UnionWithOpState{L,R,OperatorState} <: UnionAlignmentState{L,R}
valid_l::Bool
valid_r::Bool
operator_state::OperatorState
# These fields may initially be uninitialised.
latest_l::L
latest_r::R
function UnionWithOpState{L,R}(operator_state::OperatorState) where {L,R,OperatorState}
return new{L,R,OperatorState}(false, false, operator_state)
end
function UnionWithOpState{L,R}(
operator_state::OperatorState, initial_l::L, initial_r::R
) where {L,R,OperatorState}
return new{L,R,OperatorState}(true, true, operator_state, initial_l, initial_r)
end
end
mutable struct UnionWithoutOpState{L,R} <: UnionAlignmentState{L,R}
valid_l::Bool
valid_r::Bool
# These fields may initially be uninitialised.
latest_l::L
latest_r::R
function UnionWithoutOpState{L,R}() where {L,R}
return new{L,R}(false, false)
end
function UnionWithoutOpState{L,R}(initial_l::L, initial_r::R) where {L,R}
return new{L,R}(true, true, initial_l, initial_r)
end
end
operator_state(state::UnionWithOpState) = state.operator_state
operator_state(::UnionWithoutOpState) = EMPTY_NODE_STATE
function _set_l!(state::UnionAlignmentState{L}, x::L) where {L}
state.latest_l = x
state.valid_l = true
return state
end
function _set_r!(state::UnionAlignmentState{L,R}, x::R) where {L,R}
state.latest_r = x
state.valid_r = true
return state
end
function create_evaluation_state(
parents::Tuple{Node,Node}, op::BinaryNodeOp{T,UnionAlignment}
) where {T}
L = value_type(parents[1])
R = value_type(parents[2])
return if stateless_operator(op)
if has_initial_values(op)
UnionWithoutOpState{L,R}(initial_left(op), initial_right(op))
else
UnionWithoutOpState{L,R}()
end
else
operator_state = create_operator_evaluation_state(parents, op)
if has_initial_values(op)
UnionWithOpState{L,R}(operator_state, initial_left(op), initial_right(op))
else
UnionWithOpState{L,R}(operator_state)
end
end
end
@inline function _maybe_add_knot!(
node_op::NodeOp,
operator_state::NodeEvaluationState,
out_times::AbstractVector{DateTime},
out_values::AbstractVector{T},
j::Int,
time::DateTime,
in_values...,
) where {T}
# Find the output value. For a given op this will either be of type T, or Maybe{T}, and
# we can (at compile time) select the correct branch below based on `always_ticks(op)`.
out = _operator!(node_op, operator_state, time, in_values...)
return if always_ticks(node_op)
# Output value is raw, and should always be used.
@inbounds out_times[j] = time
@inbounds out_values[j] = out
j + 1
else
if valid(out)
# Add the output only if the output is valid.
@inbounds out_times[j] = time
@inbounds out_values[j] = unsafe_value(out)
j + 1
else
j
end
end
end
function run_node!(
node_op::BinaryNodeOp{T,UnionAlignment},
state::UnionAlignmentState,
::DateTime, # time_start
::DateTime, # time_end
input_l::Block,
input_r::Block,
) where {T}
@inbounds if isempty(input_l) && isempty(input_r)
# Nothing to do, since neither input has ticked.
return Block{T}()
elseif isempty(input_l) && !state.valid_l
# Left is inactive and won't tick, so nothing gets emitted. But make sure we update
# the state on the right.
_set_r!(state, last(input_r.values))
return Block{T}()
elseif isempty(input_r) && !state.valid_r
# Right is inactive and won't tick, so nothing gets emitted. But make sure we update
# the state on the left.
_set_l!(state, last(input_l.values))
return Block{T}()
end
if _equal_times(input_l, input_r)
# Times are indistinguishable
# Update the alignment state.
_set_l!(state, @inbounds last(input_l.values))
_set_r!(state, @inbounds last(input_r.values))
return _apply_fast_align_binary!(node_op, operator_state(state), input_l, input_r)
end
# Create our outputs as the maximum possible size.
nl = length(input_l)
nr = length(input_r)
max_size = nl + nr
times = _allocate_times(max_size)
values = _allocate_values(T, max_size)
# Store indices into the inputs. The index represents the next time point for
# consideration for each series.
il = 1
ir = 1
# Index into the output.
j = 1
# Loop until we exhaust inputs.
@inbounds while (il <= nl || ir <= nr)
# Store the next available time in the series, that is being pointed to by il & ir.
next_time_l = il <= nl ? input_l.times[il] : DateTime(0)
next_time_r = ir <= nr ? input_r.times[ir] : DateTime(0)
new_time = if (il <= nl && next_time_l < next_time_r) || ir > nr
# Left ticks next
_set_l!(state, input_l.values[il])
il += 1
next_time_l
elseif (ir <= nr && next_time_r < next_time_l) || il > nl
# Right ticks next
_set_r!(state, input_r.values[ir])
ir += 1
next_time_r
else
# A shared time point where neither input has been exhausted.
_set_l!(state, input_l.values[il])
_set_r!(state, input_r.values[ir])
il += 1
ir += 1
next_time_l
end
# We must only output a knot if both inputs are active.
if !state.valid_l || !state.valid_r
continue
end
# Compute and possibly output a knot.
j = _maybe_add_knot!(
node_op,
operator_state(state),
times,
values,
j,
new_time,
state.latest_l,
state.latest_r,
)
end
# Package the outputs into a block, resizing the outputs as necessary.
_trim!(times, j - 1)
_trim!(values, j - 1)
return Block(unchecked, times, values)
end
function create_evaluation_state(
parents::Tuple{Node,Node}, op::BinaryNodeOp{T,IntersectAlignment}
) where {T}
# Intersect alignment doesn't require remembering any previous state, so just return
# the operator state.
return _create_operator_evaluation_state(parents, op)
end
function run_node!(
node_op::BinaryNodeOp{T,IntersectAlignment},
operator_state::NodeEvaluationState,
::DateTime, # time_start
::DateTime, # time_end
input_l::Block,
input_r::Block,
) where {T}
if isempty(input_l) || isempty(input_r)
# Output will be empty unless both inputs have ticked.
return Block{T}()
end
if _equal_times(input_l, input_r)
# Times are indistinguishable.
return _apply_fast_align_binary!(node_op, operator_state, input_l, input_r)
end
# Create our outputs as the maximum possible size.
nl = length(input_l)
nr = length(input_r)
max_size = min(nl, nr)
times = _allocate_times(max_size)
values = _allocate_values(T, max_size)
# Store indices into the inputs. The index represents the next time point for
# consideration for each series.
il = 1
ir = 1
# Index into the output.
j = 1
# If we get to the end of either series, we know that we cannot add any more elements to
# the output.
@inbounds while (il <= nl && ir <= nr)
# Obtain the *next available* times from each entity. We know that the current
# state, and last emitted, time is strictly less than either of these.
next_time_l = input_l.times[il]
next_time_r = input_r.times[ir]
if next_time_l < next_time_r
# Left ticks next; consider the next knot.
il += 1
elseif next_time_r < next_time_l
# Right ticks next; consider the next knot.
ir += 1
else # next_time_l == next_time_r
# Shared time point, so emit a knot.
j = _maybe_add_knot!(
node_op,
operator_state,
times,
values,
j,
next_time_l,
input_l.values[il],
input_r.values[ir],
)
il += 1
ir += 1
end
end
# Package the outputs into a block, resizing the outputs as necessary.
_trim!(times, j - 1)
_trim!(values, j - 1)
return Block(unchecked, times, values)
end
abstract type LeftAlignmentState{R} <: NodeEvaluationState end
mutable struct LeftWithOpState{R,OperatorState} <: LeftAlignmentState{R}
valid_r::Bool
operator_state::OperatorState
latest_r::R
function LeftWithOpState{R}(operator_state::OperatorState) where {R,OperatorState}
return new{R,OperatorState}(false, operator_state)
end
function LeftWithOpState{R}(
operator_state::OperatorState, initial_r::R
) where {R,OperatorState}
return new{R,OperatorState}(true, operator_state, initial_r)
end
end
mutable struct LeftWithoutOpState{R} <: LeftAlignmentState{R}
valid_r::Bool
latest_r::R
LeftWithoutOpState{R}() where {R} = new{R}(false)
LeftWithoutOpState{R}(initial_r::R) where {R} = new{R}(true, initial_r)
end
operator_state(::LeftWithoutOpState) = EMPTY_NODE_STATE
operator_state(state::LeftWithOpState) = state.operator_state
function _set_r!(state::LeftAlignmentState{R}, x::R) where {R}
state.latest_r = x
state.valid_r = true
return state
end
function create_evaluation_state(
parents::Tuple{Node,Node}, op::BinaryNodeOp{T,LeftAlignment}
) where {T}
R = value_type(parents[2])
return if stateless_operator(op)
if has_initial_values(op)
LeftWithoutOpState{R}(initial_right(op))
else
LeftWithoutOpState{R}()
end
else
operator_state = create_operator_evaluation_state(parents, op)
if has_initial_values(op)
LeftWithOpState{R}(operator_state, initial_right(op))
else
LeftWithOpState{R}(operator_state)
end
end
end
function run_node!(
node_op::BinaryNodeOp{T,LeftAlignment},
state::LeftAlignmentState,
::DateTime, # time_start
::DateTime, # time_end
input_l::Block,
input_r::Block,
) where {T}
have_initial_r = state.valid_r
if isempty(input_l)
# We will not tick, but update state if necessary.
if !isempty(input_r)
_set_r!(state, @inbounds last(input_r.values))
end
return Block{T}()
elseif isempty(input_r) && !have_initial_r
# We cannot tick, since we have no values on the right. No state to update either.
return Block{T}()
end
if _equal_times(input_l, input_r)
# Times are indistinguishable.
return _apply_fast_align_binary!(node_op, operator_state(state), input_l, input_r)
end
# The most we can emit is one knot for every knot in input_l.
nl = length(input_l)
nr = length(input_r)
times = _allocate_times(nl)
values = _allocate_values(T, nl)
# Start with 0, indicating that input_r hasn't started ticking yet.
ir = 0
# The index into the output.
j = 1
@inbounds for il in 1:nl
# Consume r while it would leave us before the current time in l, or until we reach
# the end of r.
next_time_l = input_l.times[il]
while (ir < nr && input_r.times[ir + 1] <= next_time_l)
ir += 1
end
if ir > 0
j = _maybe_add_knot!(
node_op,
operator_state(state),
times,
values,
j,
next_time_l,
input_l.values[il],
input_r.values[ir],
)
elseif have_initial_r
# R hasn't ticked in this batch, but we have an initial value.
j = _maybe_add_knot!(
node_op,
operator_state(state),
times,
values,
j,
next_time_l,
input_l.values[il],
state.latest_r,
)
end
end
# Update state
if !isempty(input_r)
_set_r!(state, @inbounds last(input_r.values))
end
# Package the outputs into a block, resizing the outputs as necessary.
_trim!(times, j - 1)
_trim!(values, j - 1)
return Block(unchecked, times, values)
end
# Some thought went into how to store `latest` for the nary case.
#
# Ideally one would use a mutable heterogeneous collection (i.e. a "mutable tuple"), but
# such a thing doesn't exist in Julia. There are tricks one can use if your elements are
# isbits (see StaticArrays.MArray), but we want a solution that can work for *any* input
# Julia type.
#
# Options considered:
# 1. Nary alignment, with latest::Vector{Any} and accept that state *cannot* store latest
# values efficiently (will be a lot of runtime type checking). This WILL be slow, as
# it is in the inner loop of evaluation.
# 2. Nary alignment, and use a Tuple for storage.
# But, because this isn't mutable, will have to use `Base.setindex` to update, which
# could theoretically do a lot of allocating.
# 3. Use code generation to make Union2, Union3, Union4, ...
# This bloats the code somewhat, but would be guaranteed to be fast.
# However, there is then an arbitrary limit to the number of things that we can align.
#
# Benchmarking suggests that option 2 can actually be quite efficient in practice, since if
# we immediately assign the tuple, LLVM has the ability to re-use memory. We hence take this
# approach.
#
# In the future, we could generate a SMALL number of additional special-cases using option 3
# (if, for example, we found ourselves doing a lot of ternary alignment).
#
# Also, to simplify matters, we use a single alignment state. It is slightly less memory
# efficient, because we store a pointer for operator state even if it is unnecessary.
# `Types` will look something like Tuple{In1,In2,...}
mutable struct NaryAlignmentState{N,Types<:Tuple,OperatorState} <: NodeEvaluationState
# Since we may not have a latest value, we use the partial initialisation trick inside
# `Maybe` to avoid having to invent an unused placeholder for arbitrary types.
latest::Tuple{Vararg{Maybe}}
operator_state::OperatorState
function NaryAlignmentState{N,Types}(
operator_state::OperatorState
) where {N,Types,OperatorState}
return new{N,Types,OperatorState}(
Tuple(Maybe{T}() for T in Types.parameters), operator_state
)
end
function NaryAlignmentState{N,Types}(
operator_state::OperatorState, initial_values::Types
) where {N,Types,OperatorState}
return new{N,Types,OperatorState}(
Tuple(Maybe(v) for v in initial_values), operator_state
)
end
end
operator_state(state::NaryAlignmentState) = state.operator_state
Base.@propagate_inbounds function _set!(state::NaryAlignmentState, x, i::Integer)
# TODO Consider making a mutable Maybe type, to avoid possible reconstruction of the
# tuple? It might just end up being slower though due to extra dereferencing.
# The state tuple is not mutable, so we need to use this trick.
state.latest = Base.setindex(state.latest, Maybe(x), i)
return state
end
function create_evaluation_state(
parents::NTuple{N,Node}, op::NaryNodeOp{N,T,UnionAlignment}
) where {N,T}
# Work out the tuple of input types necessary for constructing the alignment state.
Types = Tuple{map(value_type, parents)...}
operator_state = _create_operator_evaluation_state(parents, op)
return if has_initial_values(op)
NaryAlignmentState{N,Types}(operator_state, initial_values(op))
else
NaryAlignmentState{N,Types}(operator_state)
end
end
function create_evaluation_state(
parents::NTuple{N,Node}, op::NaryNodeOp{N,T,IntersectAlignment}
) where {N,T}
# Intersect alignment doesn't require remembering any previous state, so just return
# the operator state.
return _create_operator_evaluation_state(parents, op)
end
function create_evaluation_state(
parents::NTuple{N,Node}, op::NaryNodeOp{N,T,LeftAlignment}
) where {N,T}
# Work out the tuple of input types necessary for constructing the alignment state.
# Note that we should ignore the left parent, so we only capture the rightmost M = N-1.
_, parents_r... = parents
M = N - 1
Types = Tuple{map(value_type, parents_r)...}
operator_state = _create_operator_evaluation_state(parents, op)
return if has_initial_values(op)
_, initial_values_r... = initial_values(op)
NaryAlignmentState{M,Types}(operator_state, initial_values_r)
else
NaryAlignmentState{M,Types}(operator_state)
end
end
"""Apply, assuming all `inputs` have identical alignment."""
function _apply_fast_align_nary!(
op::NaryNodeOp{N,T}, operator_state::NodeEvaluationState, inputs::NTuple{N,Block}
) where {N,T}
times = @inbounds first(inputs).times
n = length(times)
values = _allocate_values(T, n)
return if always_ticks(op)
@inbounds for i in 1:n
time = times[i]
values[i] = _operator!(
op, operator_state, time, map(x -> x.values[i], inputs)...
)
end
Block(unchecked, times, values)
else
# FIXME Implement this branch!
error("Not implemented!")
end
end
"""
equivalence_classes(f, collection) -> Vector{Vector{eltype(collection)}}
Generate the set of equivalence classes for `collection` generated by the equivalence
relation `f : T × T → Bool`.
Note that behaviour is undefined if `f` is non-transitive.
"""
function equivalence_classes(f::Function, x)
T = eltype(x)
result = Vector{Vector{T}}()
isempty(x) && return result
@inbounds for el in x
for class in result
f(el, first(class)) || continue
push!(class, el)
# Jump to "found" label below. This means that we don't need to add a new
# equivalence class.
@goto found
end
# We end up here if we didn't find an existing equivalence class for `el`, so we
# need to create a new one.
push!(result, T[el])
# Label used for escaping from the for loop above.
@label found
end
return result
end
function run_node!(
node_op::NaryNodeOp{N,T,UnionAlignment},
state::NaryAlignmentState{N},
::DateTime, # time_start
::DateTime, # time_end
inputs::Block...,
) where {N,T}
@assert N == length(inputs)
inputs_empty = map(isempty, inputs)
@inbounds if all(inputs_empty)
# Nothing to do, as no inputs have ticked.
return Block{T}()
elseif any(inputs_empty .& map(!valid, state.latest))
# There is at least one input which has an empty input and does *not* have an
# initial value.
# We need to make sure we update any states which do have inputs.
for (k, input) in enumerate(inputs)
isempty(input) && continue
_set!(state, last(input.values), k)
end
# The output will, however, be empty.
return Block{T}()
end
input_classes = equivalence_classes(_equal_times, inputs)
if length(input_classes) == 1
# All times are indistinguishable.
# Update alignment state and use fast alignment.
@inbounds for (k, input) in enumerate(inputs)
_set!(state, last(input.values), k)
end
return _apply_fast_align_nary!(node_op, operator_state(state), inputs)
end
# TODO `max_size` could be a massive overestimate.
# In practice it may be better to pick something smaller, and then increase the buffer
# size where necessary.
# We use an optimisation here, whereby we use the `_equal_times` equivalence
# relation to partition the inputs into sets which have equal times. We know that times
# that are equal can only appear once, so this avoids some double counting.
max_size = sum(x -> length(first(x)), input_classes)
times = _allocate_times(max_size)
values = _allocate_values(T, max_size)
# Indices into the inputs. The index represents the next time point for
# consideration for each series.
is = MVector{N,Int64}(ones(Int64, N))
# Index into the output.
j = 1
ns = map(length, inputs)