Projekt

Obecné

Profil

Stáhnout (7.15 KB) Statistiky
| Větev: | Tag: | Revize:
1
//
2
// Author: Roman Kalivoda
3
//
4

    
5
using System;
6
using System.Collections.Generic;
7
using ServerApp.Connection.XMLProtocolHandler;
8
using ServerApp.Parser.Parsers;
9
using Newtonsoft.Json;
10
using ServerApp.WeatherPredictionParser;
11
using ServerApp.Parser.OutputInfo;
12

    
13
namespace ServerApp.Predictor
14
{
15
    /// <summary>
16
    /// Implentation of the <c>IPredicitionController</c> interface.
17
    /// </summary>
18
    public class PredictionController : IPredictionController
19
    {
20
        /// <summary>
21
        /// Configuration of the <c>Predictor</c>
22
        /// </summary>
23
        private PredictorConfiguration Configuration;
24

    
25
        private List<IPredictor> Predictors;
26

    
27
        /// <summary>
28
        /// A reference to a data parser.
29
        /// </summary>
30
        private IDataParser DataParser;
31

    
32
        /// <summary>
33
        /// A feature extractor instance.
34
        /// </summary>
35
        private FeatureExtractor FeatureExtractor;
36

    
37
        /// <summary>
38
        /// A weather prediction parser service
39
        /// </summary>
40
        private IJsonParser weatherService;
41

    
42
        /// <summary>
43
        /// Instantiates new prediction controller.
44
        /// </summary>
45
        /// <param name="dataParser">A data parser used to get training data.</param>
46
        public PredictionController(IJsonParser weatherService, IDataParser dataParser, string pathToConfig = null)
47
        {
48
            this.weatherService = weatherService;
49
            // 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("Warning: could not find a configuration file, creating a new one:");
61
                Console.WriteLine(e.Message.PadLeft(4));
62
                this.Configuration = PredictorConfiguration.GetDefaultConfig();
63
            }
64

    
65
            this.DataParser = dataParser;
66
            this.Predictors = new List<IPredictor>();
67
            this.FeatureExtractor = new FeatureExtractor(this.DataParser, this.Configuration);
68

    
69
            for (int i = 0; i < this.Configuration.PredictorCount; i++)
70
            {
71
                Predictors.Add(new NaiveBayesClassifier());
72
            }
73
            PredictorConfiguration.SaveConfig(PredictorConfiguration.DEFAULT_CONFIG_PATH, Configuration);
74
        }
75
        public List<string> GetPredictors()
76
        {
77
            return new List<string>(this.Configuration.BuildingsToAreas.Keys);
78
        }
79

    
80
        public void Load(string locationKey = null, string path = null)
81
        {
82
            if (locationKey is null)
83
            {
84
                throw new NotImplementedException();
85
            }
86
            else
87
            {
88
                throw new NotImplementedException();
89
            }
90
        }
91

    
92
        public Response Predict(Request request)
93
        {
94
            DateTime start = new DateTime(year: request.start.year, month: request.start.month, day: request.start.day, hour: request.start.hour, minute: 0, second: 0);
95
            List<Prediction> predictions = new List<Prediction>();
96
            if (request.useEndDate)
97
            {
98
                DateTime end = new DateTime(year: request.end.year, month: request.end.month, day: request.end.day, hour: request.end.hour, minute: 0, second: 0);
99
                DateTime current = start;
100
                while (current < end)
101
                {
102
                    while (current.Hour < Date.MAX_HOUR)
103
                    {
104
                        var prediction = PredictSingle(request, current);
105
                        predictions.Add(prediction);
106
                        current = current.AddHours(this.Configuration.TimeResolution);
107
                    }
108
                    current = current.AddHours(23 - current.Hour + Date.MIN_HOUR);
109
                }
110
            } else
111
            {
112
                if (request.useWeather)
113
                {
114
                    predictions.Add(PredictSingle(request, start));
115
                }
116
            }
117
            var response = new Response();
118
            response.hoursPerSegment = Configuration.TimeResolution;
119
            response.predicitons = predictions.ToArray();
120
            return response;
121
        }
122

    
123
        private Prediction PredictSingle(Request request, DateTime current)
124
        {
125
            double[] predictedValues = new double[this.Configuration.BuildingsToAreas.Count];
126
            string[] predictedLabels = new string[this.Predictors.Count];
127
            for (int i = 0; i < this.Predictors.Count; i++)
128
            {
129
                if (request.useWeather)
130
                {
131
                    predictedLabels[i] = this.Predictors[i].Predict(new ModelInput
132
                    {
133
                        Rain = (float)request.rain,
134
                        Temp = (float)request.temperature,
135
                        Wind = (float)request.wind,
136
                        Hour = current.Hour,
137
                        Time = current
138
                    });
139
                }
140
                else
141
                {
142
                    List<WeatherInfo> weatherInfos = weatherService.GetPredictionForTime(from: current, to: current.AddHours(this.Configuration.TimeResolution));
143
                    predictedLabels[i] = this.Predictors[i].Predict(new ModelInput
144
                    {
145
                        Rain = weatherInfos[0].rain,
146
                        Temp = (float)weatherInfos[0].temp,
147
                        Wind = (float)weatherInfos[0].wind,
148
                        Hour = current.Hour,
149
                        Time = current
150
                    });
151
                }
152
            }
153
            for (int i = 0; i < predictedValues.Length; i++)
154
            {
155
                predictedValues[i] = this.FeatureExtractor.LabelToRatio(predictedLabels[this.Configuration.BuildingsToAreas[TagInfo.buildings[i]]]) * 100;
156
            }
157

    
158
            Prediction prediction = new Prediction();
159
            prediction.dateTime = new Date
160
            {
161
                year = current.Year,
162
                month = current.Month,
163
                day = current.Day,
164
                hour = current.Hour
165
            };
166
            prediction.predictions = predictedValues;
167
            return prediction;
168
        }
169

    
170
        public void Train(string locationKey = null)
171
        {
172
            if (locationKey is null)
173
            // train all predictors
174
            {
175
                DataParser.Parse(DateTime.MinValue, DateTime.MaxValue, this.Configuration.TimeResolution, wholeDay: false);
176
                for (int i = 0; i < this.Predictors.Count; i++)
177
                {
178
                    // train on all available data
179
                    List<ModelInput> data = FeatureExtractor.PrepareTrainingInput(i);
180
                    Console.WriteLine("Training predictor with {0} samples.", data.Count);
181
                    this.Predictors[i].Fit(data);
182
                }
183
            }
184
            else
185
            // train specified predictor only
186
            {
187
                throw new NotImplementedException();
188
            }
189
        }
190

    
191

    
192
    }
193
}
(7-7/8)