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 package org.jrobin.data;
27
28 import org.jrobin.core.Util;
29
30 import java.util.Arrays;
31
32 class Normalizer {
33 final private long[] timestamps;
34 final int count;
35 final long step;
36
37 Normalizer(long[] timestamps) {
38 this.timestamps = timestamps;
39 this.step = timestamps[1] - timestamps[0];
40 this.count = timestamps.length;
41 }
42
43 double[] normalize(long[] rawTimestamps, double[] rawValues) {
44 int rawCount = rawTimestamps.length;
45 long rawStep = rawTimestamps[1] - rawTimestamps[0];
46
47 if (rawCount == count && rawStep == step && rawTimestamps[0] == timestamps[0]) {
48 return getCopyOf(rawValues);
49 }
50
51 double[] values = new double[count];
52 Arrays.fill(values, Double.NaN);
53 for (int rawSeg = 0, seg = 0; rawSeg < rawCount && seg < count; rawSeg++) {
54 double rawValue = rawValues[rawSeg];
55 if (!Double.isNaN(rawValue)) {
56 long rawLeft = rawTimestamps[rawSeg] - rawStep;
57 while (seg < count && rawLeft >= timestamps[seg]) {
58 seg++;
59 }
60 boolean overlap = true;
61 for (int fillSeg = seg; overlap && fillSeg < count; fillSeg++) {
62 long left = timestamps[fillSeg] - step;
63 long t1 = Math.max(rawLeft, left);
64 long t2 = Math.min(rawTimestamps[rawSeg], timestamps[fillSeg]);
65 if (t1 < t2) {
66 values[fillSeg] = Util.sum(values[fillSeg], (t2 - t1) * rawValues[rawSeg]);
67 }
68 else {
69 overlap = false;
70 }
71 }
72 }
73 }
74 for (int seg = 0; seg < count; seg++) {
75 values[seg] /= step;
76 }
77 return values;
78 }
79
80 private static double[] getCopyOf(double[] rawValues) {
81 int n = rawValues.length;
82 double[] values = new double[n];
83 System.arraycopy(rawValues, 0, values, 0, n);
84 return values;
85 }
86 }
87