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 timeseries Y are predicted using
045 * the values of a set of time series X at some offset over some time window. X may potentially contain Y itself
046 * which turns this into an auto-regressive model augmented with extra information. Furthermore, varying window
047 * sizes and offsets may be used for each time series X.
048 * 
049 * This is all achieved with {@link SynchronisedTimeSeriesCollection} which model a set of timeseries which are
050 * synchronised.
051 * 
052 * When intitalised, the Y time series must be explicitly specified. By default the 
053 * @author Sina Samangooei (ss@ecs.soton.ac.uk)
054 *
055 */
056public class WindowedLinearRegressionAggregator implements SynchronisedTimeSeriesCollectionAggregator<
057        DoubleTimeSeries, 
058        DoubleSynchronisedTimeSeriesCollection, 
059        DoubleTimeSeries>{
060
061        private static final int DEFAULT_WINDOW_SIZE = 3;
062        private static final int DEFAULT_OFFSET = 1;
063        private LinearRegression reg;
064        private boolean autoregressive = true;
065        private List<IndependentPair<Integer,Integer>> windowOffsets;
066        private String ydataName;
067        
068        private WindowedLinearRegressionAggregator(){
069                this.windowOffsets = new ArrayList<IndependentPair<Integer,Integer>>();
070        }
071        /**
072         * Calculate the regression from the same time series inputed
073         * @param ydataName 
074         */
075        public WindowedLinearRegressionAggregator(String ydataName) {
076                this();
077                windowOffsets.add(IndependentPair.pair(DEFAULT_WINDOW_SIZE, DEFAULT_OFFSET));
078                this.ydataName = ydataName;
079        }
080        
081        /**
082         * Calculate the regression from the same time series inputed
083         * @param ydataName 
084         * @param autoregressive whether the ydata should be used in regression
085         */
086        public WindowedLinearRegressionAggregator(String ydataName,boolean autoregressive) {
087                this();
088                windowOffsets.add(IndependentPair.pair(DEFAULT_WINDOW_SIZE, DEFAULT_OFFSET));
089                this.ydataName = ydataName;
090                this.autoregressive = autoregressive;
091        }
092        
093        /**
094         * Perform regression s.t. Y = Sum(w_{0-i} * x_{0-i}) + c using the same window size
095         * for all other time series
096         * @param ydataName 
097         * @param windowsize
098         */
099        public WindowedLinearRegressionAggregator(String ydataName,int windowsize) {
100                this();
101                this.ydataName = ydataName;
102                windowOffsets.add(IndependentPair.pair(windowsize, DEFAULT_OFFSET));
103                
104        }
105        /**
106         * Perform regression s.t. Y = Sum(w_{0-i} * x_{0-i}) + c using the same window size
107         * for all other time series
108         * @param ydataName 
109         * @param windowsize
110         * @param autoregressive whether the ydata should be used in regression
111         */
112        public WindowedLinearRegressionAggregator(String ydataName,int windowsize,boolean autoregressive) {
113                this();
114                this.ydataName = ydataName;
115                windowOffsets.add(IndependentPair.pair(windowsize, DEFAULT_OFFSET));
116                this.autoregressive = autoregressive;
117                
118        }
119        
120        /**
121         * Perform regression s.t. y = Sum(w_{0-i} * x_{0-i}) + c for i from 1 to windowsize with some
122         * offset. The same windowsize and offset is used for each time series
123         * @param ydataName 
124         * @param windowsize
125         * @param offset 
126         */
127        public WindowedLinearRegressionAggregator(String ydataName,int windowsize, int offset) {
128                this();
129                this.ydataName = ydataName;
130                windowOffsets.add(IndependentPair.pair(windowsize, offset));
131                
132        }
133        
134        /**
135         * Perform regression s.t. y = Sum(w_{0-i} * x_{0-i}) + c for i from 1 to windowsize with some
136         * offset. The same windowsize and offset is used for each time series
137         * @param ydataName 
138         * @param windowsize
139         * @param offset 
140         * @param autoregressive whether the ydata should be used in regression
141         */
142        public WindowedLinearRegressionAggregator(String ydataName,int windowsize, int offset, boolean autoregressive) {
143                this();
144                this.ydataName = ydataName;
145                this.autoregressive = autoregressive;
146                windowOffsets.add(IndependentPair.pair(windowsize, offset));
147                
148        }
149        
150        /**
151         * Perform regression s.t. y = Sum(w_{0-i} * x_{0-i}) + c for i from 1 to windowsize with some
152         * offset. The same windowsize and offset is used for each time series
153         * @param ydataName 
154         * @param windowsize
155         * @param offset 
156         * @param autoregressive whether the ydata should be used in regression
157         */
158        public WindowedLinearRegressionAggregator(String ydataName,int windowsize, int offset, boolean autoregressive,DoubleSynchronisedTimeSeriesCollection other) {
159                this();
160                WindowedLinearRegressionAggregator regress = new WindowedLinearRegressionAggregator(ydataName,windowsize,offset,autoregressive);
161                regress.aggregate(other);
162                this.reg =regress.reg;
163                this.ydataName = regress.ydataName;
164                this.autoregressive = regress.autoregressive;
165                this.windowOffsets = regress.windowOffsets;
166        }
167        
168        /**
169         * Perform regression s.t. y = Sum(w_{0-i} * x_{0-i}) + c for i from 1 to windowsize with some
170         * offset. The same windowsize and offset is used for each time series
171         * @param ydataName 
172         * @param autoregressive whether the ydata should be used in regression 
173         * @param windowOffsets
174         */
175        public WindowedLinearRegressionAggregator(String ydataName,boolean autoregressive,IndependentPair<Integer,Integer> ... windowOffsets) {
176                this();
177                this.ydataName = ydataName;
178                this.autoregressive = autoregressive;
179                for (IndependentPair<Integer, Integer> independentPair : windowOffsets) {
180                        this.windowOffsets.add(independentPair);
181                }
182        }
183        
184
185//      @Override
186//      public void process(DoubleTimeSeries series) {
187//              Matrix x = new Matrix(new double[][]{ArrayUtils.longToDouble(series.getTimes())}).transpose();
188//              List<IndependentPair<double[], double[]>> instances = new ArrayList<IndependentPair<double[], double[]>>();
189//              double[] data = series.getData();
190//              
191//              for (int i = this.windowsize + (offset - 1); i < series.size(); i++) {
192//                      int start = i - this.windowsize - (offset - 1);
193////                    System.out.format("Range %d->%d (inclusive) used to calculate: %d\n",start,start+this.windowsize-1,i);
194//                      double[] datawindow = new double[this.windowsize];
195//                      System.arraycopy(data, start, datawindow, 0, this.windowsize);
196//                      instances.add(IndependentPair.pair(datawindow, new double[]{data[i]}));
197//              }
198//              if(!regdefined)
199//              {
200//                      this.reg = new LinearRegression();
201//                      this.reg.estimate(instances);
202//              }
203//              System.out.println(this.reg);
204//              Iterator<IndependentPair<double[], double[]>> instanceIter = instances.iterator();
205//              for (int i = this.windowsize + (offset - 1); i < series.size(); i++) {
206//                      data[i] = this.reg.predict(instanceIter.next().firstObject())[0];
207//              }
208//      }
209        
210        /**
211         * @return the {@link WindowedLinearRegressionAggregator}'s underlying {@link LinearRegression} model
212         */
213        public LinearRegression getRegression() {
214                return this.reg;
215        }
216
217        @Override
218        public DoubleTimeSeries aggregate(DoubleSynchronisedTimeSeriesCollection series) {
219                
220                Set<String> names = series.getNames();
221                if(!autoregressive){
222                        names.remove(ydataName);
223                }
224                DoubleTimeSeries yseries = series.series(ydataName );
225                double[] ydata = yseries.getData();
226                
227                series = series.collectionByNames(names);
228                double[] data = series.flatten();
229                if(this.windowOffsets.size() != series.nSeries() && this.windowOffsets.size() == 1){
230                        IndependentPair<Integer, Integer> offset = this.windowOffsets.get(0);
231                        return aggregteSingle(yseries.getTimes(),ydata,data,offset.firstObject(),offset.secondObject(),series.nSeries());
232                }
233                
234                return null;
235        }
236
237        private DoubleTimeSeries aggregteSingle(long[] times, double[] ydata, double[] data,int windowsize, int offset, int nseries) {
238                List<IndependentPair<double[], double[]>> instances = new ArrayList<IndependentPair<double[], double[]>>();
239                for (int i = windowsize + (offset - 1); i < ydata.length; i++) {
240                        int start = (i - windowsize - (offset - 1)) * nseries;
241//                      System.out.format("Range %d->%d (inclusive) used to calculate: %d\n",start,start+this.windowsize-1,i);
242                        double[] datawindow = new double[windowsize*nseries];
243                        System.arraycopy(data, start, datawindow, 0, windowsize*nseries);
244                        instances.add(IndependentPair.pair(datawindow, new double[]{ydata[i]}));
245                }
246                if(this.reg==null){                     
247                        this.reg = new LinearRegression();
248                        this.reg.estimate(instances);
249                }
250                
251                DoubleTimeSeries ret = new DoubleTimeSeries(times,new double[ydata.length]);
252                
253                Iterator<IndependentPair<double[], double[]>> instanceIter = instances.iterator();
254                data = ret.getData();
255                for (int i = windowsize + (offset - 1); i < ydata.length; i++) {
256                        double[] predicted = this.reg.predict(instanceIter.next().firstObject());
257                        data[i] = predicted[0];
258                }
259                return ret.get(times[windowsize + (offset-1)], times[ydata.length-1]);
260        }
261        
262        public LinearRegression getReg(){
263                return this.reg;
264        }
265
266}