Projekt

Obecné

Profil

Stáhnout (7.04 KB) Statistiky
| Větev: | Tag: | Revize:
1 ebe96ca4 Roman Kalivoda
//
2
// Author: Roman Kalivoda
3
//
4
5
using System;
6
using System.Collections.Generic;
7 d358b79e Roman Kalivoda
using ServerApp.Connection.XMLProtocolHandler;
8 ebe96ca4 Roman Kalivoda
using ServerApp.Parser.Parsers;
9 cdeee9f8 Roman Kalivoda
using Newtonsoft.Json;
10 870cd163 Roman Kalivoda
using ServerApp.WeatherPredictionParser;
11
using ServerApp.Parser.OutputInfo;
12 ebe96ca4 Roman Kalivoda
13
namespace ServerApp.Predictor
14
{
15
    /// <summary>
16
    /// Implentation of the <c>IPredicitionController</c> interface.
17
    /// </summary>
18 870cd163 Roman Kalivoda
    public class PredictionController : IPredictionController
19 ebe96ca4 Roman Kalivoda
    {
20
        /// <summary>
21 cdeee9f8 Roman Kalivoda
        /// Configuration of the <c>Predictor</c>
22 ebe96ca4 Roman Kalivoda
        /// </summary>
23 cdeee9f8 Roman Kalivoda
        private PredictorConfiguration Configuration;
24 ebe96ca4 Roman Kalivoda
25 cdeee9f8 Roman Kalivoda
        private List<IPredictor> Predictors;
26 ebe96ca4 Roman Kalivoda
27
        /// <summary>
28
        /// A reference to a data parser.
29
        /// </summary>
30 cdeee9f8 Roman Kalivoda
        private IDataParser DataParser;
31 ebe96ca4 Roman Kalivoda
32
        /// <summary>
33
        /// A feature extractor instance.
34
        /// </summary>
35 cdeee9f8 Roman Kalivoda
        private FeatureExtractor FeatureExtractor;
36 ebe96ca4 Roman Kalivoda
37 870cd163 Roman Kalivoda
        /// <summary>
38
        /// A weather prediction parser service
39
        /// </summary>
40
        private IJsonParser weatherService;
41
42 ebe96ca4 Roman Kalivoda
        /// <summary>
43
        /// Instantiates new prediction controller.
44
        /// </summary>
45
        /// <param name="dataParser">A data parser used to get training data.</param>
46 870cd163 Roman Kalivoda
        public PredictionController(IJsonParser weatherService, IDataParser dataParser, string pathToConfig = null)
47 ebe96ca4 Roman Kalivoda
        {
48 870cd163 Roman Kalivoda
            this.weatherService = weatherService;
49 cdeee9f8 Roman Kalivoda
            // load config or get the default one
50
            if (pathToConfig is null)
51
            {
52
                pathToConfig = PredictorConfiguration.DEFAULT_CONFIG_PATH;
53
            }
54
            try
55
            {
56
                string json = System.IO.File.ReadAllText(pathToConfig);
57
                this.Configuration = JsonConvert.DeserializeObject<PredictorConfiguration>(json);
58
            } catch (System.IO.IOException e)
59
            {
60
                Console.WriteLine(e.ToString());
61
                this.Configuration = PredictorConfiguration.GetDefaultConfig();
62
            }
63
64
            this.DataParser = dataParser;
65
            this.Predictors = new List<IPredictor>();
66
            this.FeatureExtractor = new FeatureExtractor(this.DataParser, this.Configuration);
67 ebe96ca4 Roman Kalivoda
68 cdeee9f8 Roman Kalivoda
            for (int i = 0; i < this.Configuration.PredictorCount; i++)
69 ebe96ca4 Roman Kalivoda
            {
70 cdeee9f8 Roman Kalivoda
                Predictors.Add(new NaiveBayesClassifier());
71 ebe96ca4 Roman Kalivoda
            }
72 cdeee9f8 Roman Kalivoda
            PredictorConfiguration.SaveConfig(PredictorConfiguration.DEFAULT_CONFIG_PATH, Configuration);
73 ebe96ca4 Roman Kalivoda
        }
74
        public List<string> GetPredictors()
75
        {
76 cdeee9f8 Roman Kalivoda
            return new List<string>(this.Configuration.BuildingsToAreas.Keys);
77 ebe96ca4 Roman Kalivoda
        }
78
79
        public void Load(string locationKey = null, string path = null)
80
        {
81
            if (locationKey is null)
82
            {
83
                throw new NotImplementedException();
84
            }
85
            else
86
            {
87
                throw new NotImplementedException();
88
            }
89
        }
90
91 d358b79e Roman Kalivoda
        public Response Predict(Request request)
92 ebe96ca4 Roman Kalivoda
        {
93 870cd163 Roman Kalivoda
            DateTime start = new DateTime(year: request.start.year, month: request.start.month, day: request.start.day, hour: request.start.hour, minute: 0, second: 0);
94
            List<Prediction> predictions = new List<Prediction>();
95
            if (request.useEndDate)
96
            {
97
                DateTime end = new DateTime(year: request.end.year, month: request.end.month, day: request.end.day, hour: request.end.hour, minute: 0, second: 0);
98
                DateTime current = start;
99
                while (current < end)
100
                {
101
                    while (current.Hour < Date.MAX_HOUR)
102
                    {
103
                        var prediction = PredictSingle(request, current);
104
                        predictions.Add(prediction);
105
                        current = current.AddHours(this.Configuration.TimeResolution);
106
                    }
107
                    current = current.AddHours(23 - current.Hour + Date.MIN_HOUR);
108
                }
109
            } else
110
            {
111
                if (request.useWeather)
112
                {
113
                    predictions.Add(PredictSingle(request, start));
114
                }
115
            }
116
            var response = new Response();
117
            response.hoursPerSegment = Configuration.TimeResolution;
118
            response.predicitons = predictions.ToArray();
119
            return response;
120 ebe96ca4 Roman Kalivoda
        }
121
122 870cd163 Roman Kalivoda
        private Prediction PredictSingle(Request request, DateTime current)
123
        {
124
            double[] predictedValues = new double[this.Configuration.BuildingsToAreas.Count];
125
            string[] predictedLabels = new string[this.Predictors.Count];
126
            for (int i = 0; i < this.Predictors.Count; i++)
127
            {
128
                if (request.useWeather)
129
                {
130
                    predictedLabels[i] = this.Predictors[i].Predict(new ModelInput
131
                    {
132
                        Rain = (float)request.rain,
133
                        Temp = (float)request.temperature,
134
                        Wind = (float)request.wind,
135
                        Hour = current.Hour,
136
                        Time = current
137
                    });
138
                }
139
                else
140
                {
141
                    List<WeatherInfo> weatherInfos = weatherService.GetPredictionForTime(from: current, to: current.AddHours(this.Configuration.TimeResolution));
142
                    predictedLabels[i] = this.Predictors[i].Predict(new ModelInput
143
                    {
144
                        Rain = weatherInfos[0].rain,
145
                        Temp = (float)weatherInfos[0].temp,
146
                        Wind = (float)weatherInfos[0].wind,
147
                        Hour = current.Hour,
148
                        Time = current
149
                    });
150
                }
151
            }
152
            for (int i = 0; i < predictedValues.Length; i++)
153
            {
154
                predictedValues[i] = this.FeatureExtractor.LabelToRatio(predictedLabels[this.Configuration.BuildingsToAreas[TagInfo.buildings[i]]]) * 100;
155
            }
156
157
            Prediction prediction = new Prediction();
158
            prediction.dateTime = new Date
159
            {
160
                year = current.Year,
161
                month = current.Month,
162
                day = current.Day,
163
                hour = current.Hour
164
            };
165
            prediction.predictions = predictedValues;
166
            return prediction;
167
        }
168 ebe96ca4 Roman Kalivoda
169
        public void Train(string locationKey = null)
170
        {
171
            if (locationKey is null)
172
            // train all predictors
173
            {
174 74bb2a59 Roman Kalivoda
                DataParser.Parse(DateTime.MinValue, DateTime.MaxValue, this.Configuration.TimeResolution, wholeDay: false);
175 cdeee9f8 Roman Kalivoda
                for (int i = 0; i < this.Predictors.Count; i++)
176 ebe96ca4 Roman Kalivoda
                {
177 662b2404 Roman Kalivoda
                    // train on all available data
178 74bb2a59 Roman Kalivoda
                    List<ModelInput> data = FeatureExtractor.PrepareTrainingInput(i);
179 cdeee9f8 Roman Kalivoda
                    Console.WriteLine("Training predictor with {0} samples.", data.Count);
180
                    this.Predictors[i].Fit(data);
181 ebe96ca4 Roman Kalivoda
                }
182 60a60164 Roman Kalivoda
            }
183
            else
184 ebe96ca4 Roman Kalivoda
            // train specified predictor only
185
            {
186
                throw new NotImplementedException();
187
            }
188
        }
189
190
191
    }
192
}