001/**
002 * Copyright (c) 2011, The University of Southampton and the individual contributors.
003 * All rights reserved.
004 *
005 * Redistribution and use in source and binary forms, with or without modification,
006 * are permitted provided that the following conditions are met:
007 *
008 *   *  Redistributions of source code must retain the above copyright notice,
009 *      this list of conditions and the following disclaimer.
010 *
011 *   *  Redistributions in binary form must reproduce the above copyright notice,
012 *      this list of conditions and the following disclaimer in the documentation
013 *      and/or other materials provided with the distribution.
014 *
015 *   *  Neither the name of the University of Southampton nor the names of its
016 *      contributors may be used to endorse or promote products derived from this
017 *      software without specific prior written permission.
018 *
019 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
020 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
021 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
022 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
023 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
024 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
025 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
026 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
027 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
028 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
029 */
030package org.openimaj.ml.timeseries.aggregator;
031
032import java.util.ArrayList;
033import java.util.Iterator;
034import java.util.List;
035import java.util.Set;
036
037import org.openimaj.ml.regression.LinearRegression;
038import org.openimaj.ml.timeseries.collection.SynchronisedTimeSeriesCollection;
039import org.openimaj.ml.timeseries.series.DoubleSynchronisedTimeSeriesCollection;
040import org.openimaj.ml.timeseries.series.DoubleTimeSeries;
041import org.openimaj.util.pair.IndependentPair;
042
043/**
044 * An implementation of a general linear regressive such that the values of a
045 * timeseries Y are predicted using the values of a set of time series X at some
046 * offset over some time window. X may potentially contain Y itself which turns
047 * this into an auto-regressive model augmented with extra information.
048 * Furthermore, varying window sizes and offsets may be used for each time
049 * series X.
050 *
051 * This is all achieved with {@link SynchronisedTimeSeriesCollection} which
052 * model a set of timeseries which are synchronised.
053 *
054 * When intitalised, the Y time series must be explicitly specified. By default
055 * the
056 *
057 * @author Sina Samangooei (ss@ecs.soton.ac.uk)
058 *
059 */
060public class WindowedLinearRegressionAggregator implements SynchronisedTimeSeriesCollectionAggregator<
061                DoubleTimeSeries,
062                DoubleSynchronisedTimeSeriesCollection,
063                DoubleTimeSeries>
064{
065
066        private static final int DEFAULT_WINDOW_SIZE = 3;
067        private static final int DEFAULT_OFFSET = 1;
068        private LinearRegression reg;
069        private boolean autoregressive = true;
070        private List<IndependentPair<Integer, Integer>> windowOffsets;
071        private String ydataName;
072
073        private WindowedLinearRegressionAggregator() {
074                this.windowOffsets = new ArrayList<IndependentPair<Integer, Integer>>();
075        }
076
077        /**
078         * Calculate the regression from the same time series inputed
079         *
080         * @param ydataName
081         */
082        public WindowedLinearRegressionAggregator(String ydataName) {
083                this();
084                windowOffsets.add(IndependentPair.pair(DEFAULT_WINDOW_SIZE, DEFAULT_OFFSET));
085                this.ydataName = ydataName;
086        }
087
088        /**
089         * Calculate the regression from the same time series inputed
090         *
091         * @param ydataName
092         * @param autoregressive
093         *            whether the ydata should be used in regression
094         */
095        public WindowedLinearRegressionAggregator(String ydataName, boolean autoregressive) {
096                this();
097                windowOffsets.add(IndependentPair.pair(DEFAULT_WINDOW_SIZE, DEFAULT_OFFSET));
098                this.ydataName = ydataName;
099                this.autoregressive = autoregressive;
100        }
101
102        /**
103         * Perform regression s.t. Y = Sum(w_{0-i} * x_{0-i}) + c using the same
104         * window size for all other time series
105         *
106         * @param ydataName
107         * @param windowsize
108         */
109        public WindowedLinearRegressionAggregator(String ydataName, int windowsize) {
110                this();
111                this.ydataName = ydataName;
112                windowOffsets.add(IndependentPair.pair(windowsize, DEFAULT_OFFSET));
113
114        }
115
116        /**
117         * Perform regression s.t. Y = Sum(w_{0-i} * x_{0-i}) + c using the same
118         * window size for all other time series
119         *
120         * @param ydataName
121         * @param windowsize
122         * @param autoregressive
123         *            whether the ydata should be used in regression
124         */
125        public WindowedLinearRegressionAggregator(String ydataName, int windowsize, boolean autoregressive) {
126                this();
127                this.ydataName = ydataName;
128                windowOffsets.add(IndependentPair.pair(windowsize, DEFAULT_OFFSET));
129                this.autoregressive = autoregressive;
130
131        }
132
133        /**
134         * Perform regression s.t. y = Sum(w_{0-i} * x_{0-i}) + c for i from 1 to
135         * windowsize with some offset. The same windowsize and offset is used for
136         * each time series
137         *
138         * @param ydataName
139         * @param windowsize
140         * @param offset
141         */
142        public WindowedLinearRegressionAggregator(String ydataName, int windowsize, int offset) {
143                this();
144                this.ydataName = ydataName;
145                windowOffsets.add(IndependentPair.pair(windowsize, offset));
146
147        }
148
149        /**
150         * Perform regression s.t. y = Sum(w_{0-i} * x_{0-i}) + c for i from 1 to
151         * windowsize with some offset. The same windowsize and offset is used for
152         * each time series
153         *
154         * @param ydataName
155         * @param windowsize
156         * @param offset
157         * @param autoregressive
158         *            whether the ydata should be used in regression
159         */
160        public WindowedLinearRegressionAggregator(String ydataName, int windowsize, int offset, boolean autoregressive) {
161                this();
162                this.ydataName = ydataName;
163                this.autoregressive = autoregressive;
164                windowOffsets.add(IndependentPair.pair(windowsize, offset));
165
166        }
167
168        /**
169         * Perform regression s.t. y = Sum(w_{0-i} * x_{0-i}) + c for i from 1 to
170         * windowsize with some offset. The same windowsize and offset is used for
171         * each time series
172         *
173         * @param ydataName
174         * @param windowsize
175         * @param offset
176         * @param autoregressive
177         *            whether the ydata should be used in regression
178         * @param other
179         */
180        public WindowedLinearRegressionAggregator(String ydataName, int windowsize, int offset, boolean autoregressive,
181                        DoubleSynchronisedTimeSeriesCollection other)
182        {
183                this();
184                final WindowedLinearRegressionAggregator regress = new WindowedLinearRegressionAggregator(ydataName, windowsize,
185                                offset, autoregressive);
186                regress.aggregate(other);
187                this.reg = regress.reg;
188                this.ydataName = regress.ydataName;
189                this.autoregressive = regress.autoregressive;
190                this.windowOffsets = regress.windowOffsets;
191        }
192
193        /**
194         * Perform regression s.t. y = Sum(w_{0-i} * x_{0-i}) + c for i from 1 to
195         * windowsize with some offset. The same windowsize and offset is used for
196         * each time series
197         *
198         * @param ydataName
199         * @param autoregressive
200         *            whether the ydata should be used in regression
201         * @param windowOffsets
202         */
203        @SafeVarargs
204        public WindowedLinearRegressionAggregator(String ydataName, boolean autoregressive,
205                        IndependentPair<Integer, Integer>... windowOffsets)
206        {
207                this();
208                this.ydataName = ydataName;
209                this.autoregressive = autoregressive;
210                for (final IndependentPair<Integer, Integer> independentPair : windowOffsets) {
211                        this.windowOffsets.add(independentPair);
212                }
213        }
214
215        // @Override
216        // public void process(DoubleTimeSeries series) {
217        // Matrix x = new Matrix(new
218        // double[][]{ArrayUtils.longToDouble(series.getTimes())}).transpose();
219        // List<IndependentPair<double[], double[]>> instances = new
220        // ArrayList<IndependentPair<double[], double[]>>();
221        // double[] data = series.getData();
222        //
223        // for (int i = this.windowsize + (offset - 1); i < series.size(); i++) {
224        // int start = i - this.windowsize - (offset - 1);
225        // //
226        // System.out.format("Range %d->%d (inclusive) used to calculate: %d\n",start,start+this.windowsize-1,i);
227        // double[] datawindow = new double[this.windowsize];
228        // System.arraycopy(data, start, datawindow, 0, this.windowsize);
229        // instances.add(IndependentPair.pair(datawindow, new double[]{data[i]}));
230        // }
231        // if(!regdefined)
232        // {
233        // this.reg = new LinearRegression();
234        // this.reg.estimate(instances);
235        // }
236        // System.out.println(this.reg);
237        // Iterator<IndependentPair<double[], double[]>> instanceIter =
238        // instances.iterator();
239        // for (int i = this.windowsize + (offset - 1); i < series.size(); i++) {
240        // data[i] = this.reg.predict(instanceIter.next().firstObject())[0];
241        // }
242        // }
243
244        /**
245         * @return the {@link WindowedLinearRegressionAggregator}'s underlying
246         *         {@link LinearRegression} model
247         */
248        public LinearRegression getRegression() {
249                return this.reg;
250        }
251
252        @Override
253        public DoubleTimeSeries aggregate(DoubleSynchronisedTimeSeriesCollection series) {
254
255                final Set<String> names = series.getNames();
256                if (!autoregressive) {
257                        names.remove(ydataName);
258                }
259                final DoubleTimeSeries yseries = series.series(ydataName);
260                final double[] ydata = yseries.getData();
261
262                series = series.collectionByNames(names);
263                final double[] data = series.flatten();
264                if (this.windowOffsets.size() != series.nSeries() && this.windowOffsets.size() == 1) {
265                        final IndependentPair<Integer, Integer> offset = this.windowOffsets.get(0);
266                        return aggregteSingle(yseries.getTimes(), ydata, data, offset.firstObject(), offset.secondObject(),
267                                        series.nSeries());
268                }
269
270                return null;
271        }
272
273        private DoubleTimeSeries aggregteSingle(long[] times, double[] ydata, double[] data, int windowsize, int offset,
274                        int nseries)
275        {
276                final List<IndependentPair<double[], double[]>> instances = new ArrayList<IndependentPair<double[], double[]>>();
277                for (int i = windowsize + (offset - 1); i < ydata.length; i++) {
278                        final int start = (i - windowsize - (offset - 1)) * nseries;
279                        // System.out.format("Range %d->%d (inclusive) used to calculate: %d\n",start,start+this.windowsize-1,i);
280                        final double[] datawindow = new double[windowsize * nseries];
281                        System.arraycopy(data, start, datawindow, 0, windowsize * nseries);
282                        instances.add(IndependentPair.pair(datawindow, new double[] { ydata[i] }));
283                }
284                if (this.reg == null) {
285                        this.reg = new LinearRegression();
286                        this.reg.estimate(instances);
287                }
288
289                final DoubleTimeSeries ret = new DoubleTimeSeries(times, new double[ydata.length]);
290
291                final Iterator<IndependentPair<double[], double[]>> instanceIter = instances.iterator();
292                data = ret.getData();
293                for (int i = windowsize + (offset - 1); i < ydata.length; i++) {
294                        final double[] predicted = this.reg.predict(instanceIter.next().firstObject());
295                        data[i] = predicted[0];
296                }
297                return ret.get(times[windowsize + (offset - 1)], times[ydata.length - 1]);
298        }
299
300        public LinearRegression getReg() {
301                return this.reg;
302        }
303
304}