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
use arrayvec::ArrayVec;
use internal::{CombinedSegmentIterator, DeltaBufferBuilder, DeltaBufferReader, DeltaSegment, OptionSegment, Rating, RatingBuffer, RatingSegment,
TimeDelta, TimePoint, TimeSpan, TimepointBuffer, get_best_rating_segments_of_2, get_best_rating_segments_of_3,
get_overlapping_rating_changepoints};
use std::cmp::min;
use std::iter::{FromIterator, once};
struct RatingLocation {
pub rating: Rating,
pub location: TimePoint,
}
pub trait ProgressHandler {
#[allow(unused_variables)]
fn init(&mut self, steps: i64) {}
fn inc(&mut self) {}
fn finish(&mut self) {}
}
pub struct Aligner {
list: Vec<TimeSpan>,
reference: Vec<TimeSpan>,
buffer_timespan: TimeSpan,
nosplit_bonus: Rating,
progress_handler_opt: Option<Box<ProgressHandler>>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Choice {
Reposition,
Fixed,
NosplitReposition,
}
impl Aligner {
pub fn new(
list: Vec<TimeSpan>,
reference: Vec<TimeSpan>,
nopsplit_bonus_normalized: f64,
mut progress_handler_opt: Option<Box<ProgressHandler>>,
) -> Option<Aligner> {
if let Some(ref mut progress_handler) = progress_handler_opt {
progress_handler.init(list.len() as i64);
}
if list.is_empty() || reference.is_empty() {
if let Some(ref mut progress_handler) = progress_handler_opt {
progress_handler.finish();
}
return None;
}
let list_timespan = list.last().unwrap().end() - list.first().unwrap().start();
let start = reference.first().unwrap().start() - list_timespan;
let end = reference.last().unwrap().end() + list_timespan;
let nopsplit_bonus_unnormalized = min(list.len(), reference.len()) as f64 * nopsplit_bonus_normalized;
assert!(start < end);
Some(Aligner {
list: list,
reference: reference,
buffer_timespan: TimeSpan::new(start, end),
nosplit_bonus: Rating::nosplit_bonus(nopsplit_bonus_unnormalized),
progress_handler_opt: progress_handler_opt,
})
}
pub fn get_start(&self) -> TimePoint {
self.buffer_timespan.start()
}
pub fn get_end(&self) -> TimePoint {
self.buffer_timespan.end()
}
pub fn get_buffer_length(&self) -> u64 {
u64::from(self.buffer_timespan.len())
}
pub fn align_all_spans(&mut self) -> Vec<TimeDelta> {
let mut all_spanstart_buffers: Vec<TimepointBuffer> = Vec::new();
let mut last_rating_buffer: RatingBuffer = RatingBuffer::init_with_one_segment(Rating::zero(), Rating::zero(), self.get_buffer_length());
for (i, time_span) in self.list.iter().cloned().enumerate() {
let next_span_opt = self.list.get(i + 1);
let optimal_startdiff_opt = next_span_opt.map(|next_span| next_span.start() - time_span.start());
let (rating_buffer, span_positions_buffer) = self.align_new_span(last_rating_buffer, time_span, optimal_startdiff_opt);
last_rating_buffer = rating_buffer;
all_spanstart_buffers.push(span_positions_buffer);
if let Some(ref mut progress_handler) = self.progress_handler_opt {
progress_handler.inc();
}
}
let mut best_end = self.get_end() - TimeDelta::one();
let mut time_span_starts = Vec::new();
for last_span_positions in all_spanstart_buffers.into_iter().rev() {
let mut reader = DeltaBufferReader::new(&last_span_positions, self.get_start());
best_end = reader.read_by_timepoint(best_end);
time_span_starts.push(best_end);
}
if let Some(ref mut progress_handler) = self.progress_handler_opt {
progress_handler.finish();
}
time_span_starts = time_span_starts.into_iter().rev().collect();
self.list
.iter()
.zip(time_span_starts.iter())
.map(|(&original_time_span, &new_start)| {
new_start - original_time_span.start()
})
.collect()
}
fn align_new_span(
&self,
prev_rating_buffer: RatingBuffer,
new_span: TimeSpan,
optimal_startdiff_opt: Option<TimeDelta>,
) -> (RatingBuffer, TimepointBuffer) {
assert!(prev_rating_buffer.len() == self.get_buffer_length());
let overlapping_rating = self.get_compressed_overlapping_ratings(self.get_start(), self.get_end(), new_span.len());
let rating_by_repositioning = RatingBuffer::combined_add(&overlapping_rating, &prev_rating_buffer);
match optimal_startdiff_opt {
Some(optimal_startdiff) => self.get_next_lane_with_nosplit(&rating_by_repositioning, optimal_startdiff),
None => self.get_next_lane_without_nosplit(&rating_by_repositioning),
}
}
fn get_next_lane<I1, I2, F>(
&self,
optimal_startdiff: TimeDelta,
reposition_rating_iter: I1,
nosplit_rating_iter: I2,
get_maxrat_segments: F,
) -> (RatingBuffer, TimepointBuffer)
where
I1: Iterator<Item = RatingSegment>,
I2: Iterator<Item = OptionSegment<RatingSegment>>,
F: Fn(RatingSegment,
RatingSegment,
Option<RatingSegment>,
Option<Choice>) -> ArrayVec<[(RatingSegment, Choice); 3]>,
{
let mut rating_builder = DeltaBufferBuilder::<Rating, Rating>::new();
let mut spanstart_builder = DeltaBufferBuilder::<TimePoint, TimeDelta>::new();
let mut segstart_timepoint = self.get_start();
let mut past_max: RatingLocation = RatingLocation {
rating: Rating::zero(),
location: segstart_timepoint,
};
let mut last_absolute_best_choice: Option<Choice> = None;
for (reposition_rating_seg, nosplit_reposition_rating) in CombinedSegmentIterator::new(reposition_rating_iter, nosplit_rating_iter) {
if reposition_rating_seg.is_decreasing() && reposition_rating_seg.first_value() > past_max.rating {
past_max.rating = reposition_rating_seg.first_value();
past_max.location = segstart_timepoint;
}
let fixed_rating_seg = DeltaSegment::new(past_max.rating, Rating::zero(), reposition_rating_seg.len());
let maxrat_segs = get_maxrat_segments(
reposition_rating_seg,
fixed_rating_seg,
nosplit_reposition_rating,
last_absolute_best_choice,
);
last_absolute_best_choice = if maxrat_segs.len() == 1 {
Some(maxrat_segs[0].1)
} else {
None
};
for (maxrat_seg, choice) in maxrat_segs {
let (spanstart_seg_timepoint, spanstart_seg_delta) = match choice {
Choice::Reposition => (segstart_timepoint, TimeDelta::one()),
Choice::NosplitReposition => (segstart_timepoint - optimal_startdiff, TimeDelta::one()),
Choice::Fixed => (past_max.location, TimeDelta::zero()),
};
let new_spanstart_segment = DeltaSegment::new(
spanstart_seg_timepoint,
spanstart_seg_delta,
maxrat_seg.len(),
);
rating_builder.add_segment(maxrat_seg);
spanstart_builder.add_segment(new_spanstart_segment);
segstart_timepoint += TimeDelta::one() * maxrat_seg.len() as i64;
}
if past_max.rating < reposition_rating_seg.last_value() {
past_max.rating = reposition_rating_seg.last_value();
past_max.location = segstart_timepoint - TimeDelta::one();
}
}
(rating_builder.get_buffer(), spanstart_builder.get_buffer())
}
fn get_next_lane_without_nosplit(&self, reposition_rating_buffer: &RatingBuffer) -> (RatingBuffer, TimepointBuffer) {
self.get_next_lane(
TimeDelta::zero(),
reposition_rating_buffer.iter_segments().cloned(),
once(OptionSegment::NoneSeg::<RatingSegment>(
self.get_buffer_length(),
)),
Self::get_segments_and_choices_with_nosplit,
)
}
fn get_segments_and_choices_without_nosplit(
reposition_rating_seg: RatingSegment,
fixed_rating_seg: RatingSegment,
_: Option<Choice>,
) -> ArrayVec<[(RatingSegment, Choice); 3]> {
let compared_segs = [reposition_rating_seg, fixed_rating_seg];
let corresponding_choices = [Choice::Reposition, Choice::Fixed];
get_best_rating_segments_of_2(compared_segs, corresponding_choices)
}
fn get_segments_and_choices_with_nosplit(
reposition_rating_seg: RatingSegment,
fixed_rating_seg: RatingSegment,
nosplit_rating_seg_opt: Option<RatingSegment>,
last_absolute_best_choice: Option<Choice>,
) -> ArrayVec<[(RatingSegment, Choice); 3]> {
let nosplit_rating_seg = match nosplit_rating_seg_opt {
Some(x) => x,
None => {
return Self::get_segments_and_choices_without_nosplit(
reposition_rating_seg,
fixed_rating_seg,
last_absolute_best_choice,
);
}
};
match last_absolute_best_choice {
Some(Choice::Reposition) => {
if reposition_rating_seg.is_greatequal(nosplit_rating_seg) && reposition_rating_seg.is_greatequal(fixed_rating_seg) {
return ArrayVec::from_iter(
[(reposition_rating_seg, Choice::Reposition)]
.into_iter()
.cloned(),
);
}
}
Some(Choice::NosplitReposition) => {
if nosplit_rating_seg.is_greatequal(reposition_rating_seg) && nosplit_rating_seg.is_greatequal(fixed_rating_seg) {
return ArrayVec::from_iter(
[(nosplit_rating_seg, Choice::NosplitReposition)]
.into_iter()
.cloned(),
);
}
}
Some(Choice::Fixed) => {
if fixed_rating_seg.is_greatequal(reposition_rating_seg) && fixed_rating_seg.is_greatequal(nosplit_rating_seg) {
return ArrayVec::from_iter([(fixed_rating_seg, Choice::Fixed)].into_iter().cloned());
}
}
None => {}
}
let compared_segs = [reposition_rating_seg, nosplit_rating_seg, fixed_rating_seg];
let corresponding_choices = [Choice::Reposition, Choice::NosplitReposition, Choice::Fixed];
get_best_rating_segments_of_3(compared_segs, corresponding_choices)
}
fn get_next_lane_with_nosplit(&self, reposition_rating_buffer: &RatingBuffer, optimal_startdiff: TimeDelta) -> (RatingBuffer, TimepointBuffer) {
let dummy_segment = OptionSegment::NoneSeg(optimal_startdiff.into());
let bonus_segments_iter = reposition_rating_buffer.iter_segments().map(|&x| {
OptionSegment::SomeSeg(x + self.nosplit_bonus)
});
let shifted_bonus_segments_iter = once(dummy_segment).chain(bonus_segments_iter);
self.get_next_lane(
optimal_startdiff,
reposition_rating_buffer.iter_segments().cloned(),
shifted_bonus_segments_iter,
Self::get_segments_and_choices_with_nosplit,
)
}
fn get_compressed_overlapping_ratings(&self, start1: TimePoint, start2: TimePoint, length: TimeDelta) -> RatingBuffer {
assert!(start1 <= start2);
let mut builder = DeltaBufferBuilder::new();
let mut timepoints: [Vec<(Rating, TimePoint)>; 4] = [Vec::new(), Vec::new(), Vec::new(), Vec::new()];
for &ref_ts in &self.reference {
let changepoints = get_overlapping_rating_changepoints(length, ref_ts);
timepoints[0].push(changepoints[0]);
timepoints[1].push(changepoints[1]);
timepoints[2].push(changepoints[2]);
timepoints[3].push(changepoints[3]);
}
let mut iterators: ArrayVec<[_; 4]> = timepoints.into_iter()
.cloned()
.map(|v| v.into_iter().peekable())
.collect();
let mut first_timepoint: Option<TimePoint> = None;
let mut last_timepoint: Option<TimePoint> = None;
let mut current_abs = Rating::zero();
let mut current_delta = Rating::zero();
loop {
let next_timepoints: ArrayVec<[(usize, (Rating, TimePoint)); 4]> =
iterators.iter_mut()
.enumerate()
.map(|(i, iter)| iter.peek().map(|&v| (i, v)))
.filter_map(|opt| opt)
.collect();
let next_changepoint_opt = next_timepoints.into_iter().min_by_key::<TimePoint, _>(
|a| (a.1).1,
);
let (next_id, (next_rating_delta, next_timepoint)) = match next_changepoint_opt {
Some(next_changepoint) => next_changepoint,
None => break,
};
if first_timepoint.is_none() {
first_timepoint = Some(next_timepoint)
};
if let Some(last_timepoint) = last_timepoint {
let len: u64 = u64::from(next_timepoint - last_timepoint);
builder.add_segment(DeltaSegment::new(current_abs, current_delta, len));
current_abs += current_delta * len as i64;
}
current_delta += next_rating_delta;
last_timepoint = Some(next_timepoint);
iterators[next_id].next();
}
assert_eq!(current_abs, Rating::zero());
assert_eq!(current_delta, Rating::zero());
builder.add_segment(DeltaSegment::new(current_abs, current_delta, 1));
match (first_timepoint, last_timepoint) {
(Some(first_timepoint), Some(_)) => {
builder.get_buffer().with_new_borders(
i64::from(start1 - first_timepoint),
i64::from(start2 - start1),
)
}
_ => unreachable!(),
}
}
#[cfg(test)]
fn get_compressed_overlapping_ratings_slow(&self, start1: TimePoint, start2: TimePoint, length: TimeDelta) -> RatingBuffer {
let istart1: i64 = start1.into();
let istart2: i64 = start2.into();
let mut rating_buffer_builder = DeltaBufferBuilder::new();
for istart in istart1..istart2 {
let start = TimePoint::from(istart);
let span = TimeSpan::new(start, start + length);
let rating: Rating = self.reference
.iter()
.map(|ref_ts| {
let num_overlapping_segments: i64 = ref_ts.get_overlapping_length(span).into();
let single_segment_rating = Rating::from_overlapping_spans(span.len(), ref_ts.len());
single_segment_rating * num_overlapping_segments
})
.sum();
rating_buffer_builder.add_segment(RatingSegment::new(rating, Rating::zero(), 1));
}
rating_buffer_builder.get_buffer()
}
}
#[cfg(test)]
mod tests {
use super::*;
use rand;
use rand::Rng;
use tests::get_random_prepared_test_time_spans;
fn get_dummy_aligner() -> Aligner {
loop {
let reference_ts = get_random_prepared_test_time_spans();
let incorrect_ts = get_random_prepared_test_time_spans();
if let Some(a) = Aligner::new(reference_ts, incorrect_ts, 0.03, None) {
return a;
}
}
}
#[test]
fn run_aligner() {
for _ in 0..20 {
get_dummy_aligner().align_all_spans();
}
}
#[test]
fn get_compressed_overlapping_ratings() {
let mut rng = rand::thread_rng();
for _ in 0..30 {
let aligner = get_dummy_aligner();
let len: i64 = (rng.next_u32() % 100) as i64;
let rating_buffer1 = aligner.get_compressed_overlapping_ratings(
aligner.get_start(),
aligner.get_end(),
TimeDelta::one() * len,
);
let rating_buffer2 = aligner.get_compressed_overlapping_ratings_slow(
aligner.get_start(),
aligner.get_end(),
TimeDelta::one() * len,
);
assert_eq!(
rating_buffer1.iter().collect::<Vec<_>>(),
rating_buffer2.iter().collect::<Vec<_>>()
);
}
}
}