835aeff05bce6dd34bbf755a8ff228a9d2da7be9
[WebKit-https.git] / Websites / perf.webkit.org / public / v2 / app.js
1 window.App = Ember.Application.create();
2
3 App.Router.map(function () {
4     this.resource('customDashboard', {path: 'dashboard/custom'});
5     this.resource('dashboard', {path: 'dashboard/:name'});
6     this.resource('charts', {path: 'charts'});
7     this.resource('analysis', {path: 'analysis'});
8     this.resource('analysisTask', {path: 'analysis/task/:taskId'});
9 });
10
11 App.DashboardRow = Ember.Object.extend({
12     header: null,
13     cells: [],
14
15     init: function ()
16     {
17         this._super();
18
19         var cellsInfo = this.get('cellsInfo') || [];
20         var columnCount = this.get('columnCount');
21         while (cellsInfo.length < columnCount)
22             cellsInfo.push([]);
23
24         this.set('cells', cellsInfo.map(this._createPane.bind(this)));
25     },
26     addPane: function (paneInfo)
27     {
28         var pane = this._createPane(paneInfo);
29         this.get('cells').pushObject(pane);
30         this.set('columnCount', this.get('columnCount') + 1);
31     },
32     _createPane: function (paneInfo)
33     {
34         if (!paneInfo || !paneInfo.length || (!paneInfo[0] && !paneInfo[1]))
35             paneInfo = null;
36
37         var pane = App.Pane.create({
38             store: this.get('store'),
39             platformId: paneInfo ? paneInfo[0] : null,
40             metricId: paneInfo ? paneInfo[1] : null,
41         });
42
43         return App.DashboardPaneProxyForPicker.create({content: pane});
44     },
45 });
46
47 App.DashboardPaneProxyForPicker = Ember.ObjectProxy.extend({
48     _platformOrMetricIdChanged: function ()
49     {
50         var self = this;
51         App.buildPopup(this.get('store'), 'choosePane', this)
52             .then(function (platforms) { self.set('pickerData', platforms); });
53     }.observes('platformId', 'metricId').on('init'),
54     paneList: function () {
55         return App.encodePrettifiedJSON([[this.get('platformId'), this.get('metricId'), null, null, null, null, null]]);
56     }.property('platformId', 'metricId'),
57 });
58
59 App.IndexRoute = Ember.Route.extend({
60     beforeModel: function ()
61     {
62         var self = this;
63         App.Manifest.fetch(this.store).then(function () {
64             self.transitionTo('dashboard', App.Manifest.defaultDashboardName());
65         });
66     },
67 });
68
69 App.DashboardRoute = Ember.Route.extend({
70     model: function (param)
71     {
72         return App.Manifest.fetch(this.store).then(function () {
73             return App.Manifest.dashboardByName(param.name);
74         });
75     },
76 });
77
78 App.CustomDashboardRoute = Ember.Route.extend({
79     controllerName: 'dashboard',
80     model: function (param)
81     {
82         return this.store.createRecord('dashboard', {serialized: param.grid});
83     },
84     renderTemplate: function()
85     {
86         this.render('dashboard');
87     }
88 });
89
90 App.DashboardController = Ember.Controller.extend({
91     queryParams: ['grid', 'numberOfDays'],
92     headerColumns: [],
93     rows: [],
94     numberOfDays: 7,
95     editMode: false,
96
97     modelChanged: function ()
98     {
99         var dashboard = this.get('model');
100         if (!dashboard)
101             return;
102
103         var headerColumns = dashboard.get('headerColumns');
104         this.set('headerColumns', headerColumns);
105         var columnCount = headerColumns.length;
106         this.set('columnCount', columnCount);
107
108         var store = this.store;
109         this.set('rows', dashboard.get('rows').map(function (rowParam) {
110             return App.DashboardRow.create({
111                 store: store,
112                 header: rowParam[0],
113                 cellsInfo: rowParam.slice(1),
114                 columnCount: columnCount,
115             })
116         }));
117
118         this.set('emptyRow', new Array(columnCount));
119     }.observes('model').on('init'),
120
121     computeGrid: function()
122     {
123         var headers = this.get('headerColumns').map(function (header) { return header.label; });
124         var table = [headers].concat(this.get('rows').map(function (row) {
125             return [row.get('header')].concat(row.get('cells').map(function (pane) {
126                 var platformAndMetric = [pane.get('platformId'), pane.get('metricId')];
127                 return platformAndMetric[0] || platformAndMetric[1] ? platformAndMetric : [];
128             }));
129         }));
130         return JSON.stringify(table);
131     },
132
133     _sharedDomainChanged: function ()
134     {
135         var numberOfDays = this.get('numberOfDays');
136         if (!numberOfDays)
137             return;
138
139         numberOfDays = parseInt(numberOfDays);
140         var present = Date.now();
141         var past = present - numberOfDays * 24 * 3600 * 1000;
142         this.set('since', past);
143         this.set('sharedDomain', [past, present]);
144     }.observes('numberOfDays').on('init'),
145
146     actions: {
147         setNumberOfDays: function (numberOfDays)
148         {
149             this.set('numberOfDays', numberOfDays);
150         },
151         choosePane: function (param)
152         {
153             var pane = param.position;
154             pane.set('platformId', param.platform.get('id'));
155             pane.set('metricId', param.metric.get('id'));
156         },
157         addColumn: function ()
158         {
159             this.get('headerColumns').pushObject({
160                 label: this.get('newColumnHeader'),
161                 index: this.get('headerColumns').length,
162             });
163             this.get('rows').forEach(function (row) {
164                 row.addPane();
165             });
166             this.set('newColumnHeader', null);
167         },
168         removeColumn: function (index)
169         {
170             this.get('headerColumns').removeAt(index);
171             this.get('rows').forEach(function (row) {
172                 row.get('cells').removeAt(index);
173             });
174         },
175         addRow: function ()
176         {
177             this.get('rows').pushObject(App.DashboardRow.create({
178                 store: this.store,
179                 header: this.get('newRowHeader'),
180                 columnCount: this.get('columnCount'),
181             }));
182             this.set('newRowHeader', null);
183         },
184         removeRow: function (row)
185         {
186             this.get('rows').removeObject(row);
187         },
188         resetPane: function (pane)
189         {
190             pane.set('platformId', null);
191             pane.set('metricId', null);
192         },
193         toggleEditMode: function ()
194         {
195             this.toggleProperty('editMode');
196             if (this.get('editMode'))
197                 this.transitionToRoute('dashboard', 'custom', {name: null, queryParams: {grid: this.computeGrid()}});
198             else
199                 this.set('grid', this.computeGrid());
200         },
201     },
202
203     init: function ()
204     {
205         this._super();
206         App.Manifest.fetch(this.get('store'));
207     }
208 });
209
210 App.NumberOfDaysControlView = Ember.View.extend({
211     classNames: ['controls'],
212     templateName: 'number-of-days-controls',
213     didInsertElement: function ()
214     {
215         this._matchingElements(this._previousNumberOfDaysClass).addClass('active');
216     },
217     _numberOfDaysChanged: function ()
218     {
219         this._matchingElements(this._previousNumberOfDaysClass).removeClass('active');
220
221         var newNumberOfDaysClass = 'numberOfDaysIs' + this.get('numberOfDays');
222         this._matchingElements(this._previousNumberOfDaysClass).addClass('active');
223         this._previousNumberOfDaysClass = newNumberOfDaysClass;
224     }.observes('numberOfDays').on('init'),
225     _matchingElements: function (className)
226     {
227         var element = this.get('element');
228         if (!element)
229             return $([]);
230         return $(element.getElementsByClassName(className));
231     }
232 });
233
234 App.StartTimeSliderView = Ember.View.extend({
235     templateName: 'start-time-slider',
236     classNames: ['start-time-slider'],
237     startTime: Date.now() - 7 * 24 * 3600 * 1000,
238     oldestStartTime: null,
239     _numberOfDaysView: null,
240     _slider: null,
241     _startTimeInSlider: null,
242     _currentNumberOfDays: null,
243     _MILLISECONDS_PER_DAY: 24 * 3600 * 1000,
244
245     didInsertElement: function ()
246     {
247         this.oldestStartTime = Date.now() - 365 * 24 * 3600 * 1000;
248         this._slider = $(this.get('element')).find('input');
249         this._numberOfDaysView = $(this.get('element')).find('.numberOfDays');
250         this._sliderRangeChanged();
251         this._slider.change(this._sliderMoved.bind(this));
252     },
253     _sliderRangeChanged: function ()
254     {
255         var minimumNumberOfDays = 1;
256         var maximumNumberOfDays = this._timeInPastToNumberOfDays(this.get('oldestStartTime'));
257         var precision = 1000; // FIXME: Compute this from maximumNumberOfDays.
258         var slider = this._slider;
259         slider.attr('min', Math.floor(Math.log(Math.max(1, minimumNumberOfDays)) * precision) / precision);
260         slider.attr('max', Math.ceil(Math.log(maximumNumberOfDays) * precision) / precision);
261         slider.attr('step', 1 / precision);
262         this._startTimeChanged();
263     }.observes('oldestStartTime'),
264     _sliderMoved: function ()
265     {
266         this._currentNumberOfDays = Math.round(Math.exp(this._slider.val()));
267         this._numberOfDaysView.text(this._currentNumberOfDays);
268         this._startTimeInSlider = this._numberOfDaysToTimeInPast(this._currentNumberOfDays);
269         this.set('startTime', this._startTimeInSlider);
270     },
271     _startTimeChanged: function ()
272     {
273         var startTime = this.get('startTime');
274         if (startTime == this._startTimeSetBySlider)
275             return;
276         this._currentNumberOfDays = this._timeInPastToNumberOfDays(startTime);
277
278         if (this._slider) {
279             this._numberOfDaysView.text(this._currentNumberOfDays);
280             this._slider.val(Math.log(this._currentNumberOfDays));
281             this._startTimeInSlider = startTime;
282         }
283     }.observes('startTime').on('init'),
284     _timeInPastToNumberOfDays: function (timeInPast)
285     {
286         return Math.max(1, Math.round((Date.now() - timeInPast) / this._MILLISECONDS_PER_DAY));
287     },
288     _numberOfDaysToTimeInPast: function (numberOfDays)
289     {
290         return Date.now() - numberOfDays * this._MILLISECONDS_PER_DAY;
291     },
292 });
293
294 App.Pane = Ember.Object.extend({
295     platformId: null,
296     platform: null,
297     metricId: null,
298     metric: null,
299     selectedItem: null,
300     selectedPoints: null,
301     hoveredOrSelectedItem: null,
302     showFullYAxis: false,
303     searchCommit: function (repository, keyword) {
304         var self = this;
305         var repositoryId = repository.get('id');
306         CommitLogs.fetchForTimeRange(repositoryId, null, null, keyword).then(function (commits) {
307             if (self.isDestroyed || !self.get('chartData') || !commits.length)
308                 return;
309             var currentRuns = self.get('chartData').current.series();
310             if (!currentRuns.length)
311                 return;
312
313             var highlightedItems = {};
314             var commitIndex = 0;
315             for (var runIndex = 0; runIndex < currentRuns.length && commitIndex < commits.length; runIndex++) {
316                 var measurement = currentRuns[runIndex].measurement;
317                 var commitTime = measurement.commitTimeForRepository(repositoryId);
318                 if (!commitTime)
319                     continue;
320                 if (commits[commitIndex].time <= commitTime) {
321                     highlightedItems[measurement.id()] = true;
322                     do {
323                         commitIndex++;
324                     } while (commitIndex < commits.length && commits[commitIndex].time <= commitTime);
325                 }
326             }
327
328             self.set('highlightedItems', highlightedItems);
329         }, function () {
330             // FIXME: Report errors
331             this.set('highlightedItems', {});
332         });
333     },
334     _fetch: function () {
335         var platformId = this.get('platformId');
336         var metricId = this.get('metricId');
337         if (!platformId && !metricId) {
338             this.set('empty', true);
339             return;
340         }
341         this.set('empty', false);
342         this.set('platform', null);
343         this.set('chartData', null);
344         this.set('metric', null);
345         this.set('failure', null);
346
347         if (!this._isValidId(platformId))
348             this.set('failure', platformId ? 'Invalid platform id:' + platformId : 'Platform id was not specified');
349         else if (!this._isValidId(metricId))
350             this.set('failure', metricId ? 'Invalid metric id:' + metricId : 'Metric id was not specified');
351         else {
352             var self = this;
353             var useCache = true;
354             App.Manifest.fetchRunsWithPlatformAndMetric(this.get('store'), platformId, metricId, null, useCache)
355                 .then(function (result) {
356                     if (result || result.shouldRefetch)
357                         self.refetchRuns(platformId, metricId);
358                     else
359                         self._didFetchRuns(result);
360                 }, this._handleFetchErrors.bind(this, platformId, metricId));
361             this.fetchAnalyticRanges();
362         }
363     }.observes('platformId', 'metricId').on('init'),
364     refetchRuns: function (platformId, metricId) {
365         if (!platformId)
366             platformId = this.get('platform').get('id');
367         if (!metricId)
368             metricId = this.get('metric').get('id');
369         Ember.assert('refetchRuns should be called only after platform and metric are resolved', platformId && metricId);
370
371         var useCache = false;
372         App.Manifest.fetchRunsWithPlatformAndMetric(this.get('store'), platformId, metricId, null, useCache)
373             .then(this._didFetchRuns.bind(this), this._handleFetchErrors.bind(this, platformId, metricId));
374     },
375     _didFetchRuns: function (result)
376     {
377         this.set('platform', result.platform);
378         this.set('metric', result.metric);
379         this._setNewChartData(result.data);
380     },
381     _setNewChartData: function (chartData)
382     {
383         var newChartData = {};
384         for (var property in chartData)
385             newChartData[property] = chartData[property];
386
387         var showOutlier = this.get('showOutlier');
388         newChartData.showOutlier(showOutlier);
389         this.set('chartData', newChartData);
390         this._updateMovingAverageAndEnvelope();
391
392         if (!this.get('anomalyDetectionStrategies').filterBy('enabled').length)
393             this._highlightPointsMarkedAsOutlier(newChartData);
394     },
395     _highlightPointsMarkedAsOutlier: function (newChartData)
396     {
397         var data = newChartData.current.series();
398         var items = {};
399         for (var i = 0; i < data.length; i++) {
400             if (data[i].measurement.markedOutlier())
401                 items[data[i].measurement.id()] = true;
402         }
403
404         this.set('highlightedItems', items);
405     },
406     _handleFetchErrors: function (platformId, metricId, result)
407     {
408         if (!result || typeof(result) === "string")
409             this.set('failure', 'Failed to fetch the JSON with an error: ' + result);
410         else if (!result.platform)
411             this.set('failure', 'Could not find the platform "' + platformId + '"');
412         else if (!result.metric)
413             this.set('failure', 'Could not find the metric "' + metricId + '"');
414         else
415             this.set('failure', 'An internal error');
416     },
417     fetchAnalyticRanges: function ()
418     {
419         var platformId = this.get('platformId');
420         var metricId = this.get('metricId');
421         var self = this;
422         this.get('store')
423             .find('analysisTask', {platform: platformId, metric: metricId})
424             .then(function (tasks) {
425                 self.set('analyticRanges', tasks.filter(function (task) { return task.get('startRun') && task.get('endRun'); }));
426             });
427     },
428     ranges: function ()
429     {
430         return this.getWithDefault('analyticRanges', []).concat(this.getWithDefault('testRangeCandidates', []));
431     }.property('analyticRanges', 'testRangeCandidates'),
432     _isValidId: function (id)
433     {
434         if (typeof(id) == "number")
435             return true;
436         if (typeof(id) == "string")
437             return !!id.match(/^[A-Za-z0-9_]+$/);
438         return false;
439     },
440     computeStatus: function (currentPoint, previousPoint)
441     {
442         var chartData = this.get('chartData');
443         var diffFromBaseline = this._relativeDifferentToLaterPointInTimeSeries(currentPoint, chartData.baseline);
444         var diffFromTarget = this._relativeDifferentToLaterPointInTimeSeries(currentPoint, chartData.target);
445
446         var label = '';
447         var className = '';
448         var formatter = d3.format('.3p');
449
450         var smallerIsBetter = chartData.smallerIsBetter;
451         if (diffFromBaseline !== undefined && diffFromBaseline > 0 == smallerIsBetter) {
452             label = formatter(Math.abs(diffFromBaseline)) + ' ' + (smallerIsBetter ? 'above' : 'below') + ' baseline';
453             className = 'worse';
454         } else if (diffFromTarget !== undefined && diffFromTarget < 0 == smallerIsBetter) {
455             label = formatter(Math.abs(diffFromTarget)) + ' ' + (smallerIsBetter ? 'below' : 'above') + ' target';
456             className = 'better';
457         } else if (diffFromTarget !== undefined)
458             label = formatter(Math.abs(diffFromTarget)) + ' until target';
459
460         var valueDelta = null;
461         var relativeDelta = null;
462         if (previousPoint) {
463             valueDelta = chartData.deltaFormatter(currentPoint.value - previousPoint.value);
464             relativeDelta = d3.format('+.2p')((currentPoint.value - previousPoint.value) / previousPoint.value);
465         }
466         return {
467             className: className,
468             label: label,
469             currentValue: chartData.formatter(currentPoint.value),
470             valueDelta: valueDelta,
471             relativeDelta: relativeDelta,
472         };
473     },
474     _relativeDifferentToLaterPointInTimeSeries: function (currentPoint, timeSeries)
475     {
476         if (!currentPoint || !timeSeries)
477             return undefined;
478
479         var referencePoint = timeSeries.findPointAfterTime(currentPoint.time);
480         if (!referencePoint)
481             return undefined;
482
483         return (currentPoint.value - referencePoint.value) / referencePoint.value;
484     },
485     latestStatus: function ()
486     {
487         var chartData = this.get('chartData');
488         if (!chartData || !chartData.current)
489             return null;
490
491         var lastPoint = chartData.current.lastPoint();
492         if (!lastPoint)
493             return null;
494
495         return this.computeStatus(lastPoint, chartData.current.previousPoint(lastPoint));
496     }.property('chartData'),
497     updateStatisticsTools: function ()
498     {
499         var movingAverageStrategies = Statistics.MovingAverageStrategies.map(this._cloneStrategy.bind(this));
500         this.set('movingAverageStrategies', [{label: 'None'}].concat(movingAverageStrategies));
501         this.set('chosenMovingAverageStrategy', this._configureStrategy(movingAverageStrategies, this.get('movingAverageConfig')));
502
503         var envelopingStrategies = Statistics.EnvelopingStrategies.map(this._cloneStrategy.bind(this));
504         this.set('envelopingStrategies', [{label: 'None'}].concat(envelopingStrategies));
505         this.set('chosenEnvelopingStrategy', this._configureStrategy(envelopingStrategies, this.get('envelopingConfig')));
506
507         var testRangeSelectionStrategies = Statistics.TestRangeSelectionStrategies.map(this._cloneStrategy.bind(this));
508         this.set('testRangeSelectionStrategies', [{label: 'None'}].concat(testRangeSelectionStrategies));
509         this.set('chosenTestRangeSelectionStrategy', this._configureStrategy(testRangeSelectionStrategies, this.get('testRangeSelectionConfig')));
510
511         var anomalyDetectionStrategies = Statistics.AnomalyDetectionStrategy.map(this._cloneStrategy.bind(this));
512         this.set('anomalyDetectionStrategies', anomalyDetectionStrategies);
513     }.on('init'),
514     _cloneStrategy: function (strategy)
515     {
516         var parameterList = (strategy.parameterList || []).map(function (param) { return Ember.Object.create(param); });
517         return Ember.Object.create({
518             id: strategy.id,
519             label: strategy.label,
520             isSegmentation: strategy.isSegmentation,
521             description: strategy.description,
522             parameterList: parameterList,
523             execute: strategy.execute,
524         });
525     },
526     _configureStrategy: function (strategies, config)
527     {
528         if (!config || !config[0])
529             return null;
530
531         var id = config[0];
532         var chosenStrategy = strategies.find(function (strategy) { return strategy.id == id });
533         if (!chosenStrategy)
534             return null;
535
536         if (chosenStrategy.parameterList) {
537             for (var i = 0; i < chosenStrategy.parameterList.length; i++)
538                 chosenStrategy.parameterList[i].value = parseFloat(config[i + 1]);
539         }
540
541         return chosenStrategy;
542     },
543     _updateMovingAverageAndEnvelope: function ()
544     {
545         var chartData = this.get('chartData');
546         if (!chartData)
547             return;
548
549         var movingAverageStrategy = this.get('chosenMovingAverageStrategy');
550         this._updateStrategyConfigIfNeeded(movingAverageStrategy, 'movingAverageConfig');
551
552         var envelopingStrategy = this.get('chosenEnvelopingStrategy');
553         this._updateStrategyConfigIfNeeded(envelopingStrategy, 'envelopingConfig');
554
555         var testRangeSelectionStrategy = this.get('chosenTestRangeSelectionStrategy');
556         this._updateStrategyConfigIfNeeded(testRangeSelectionStrategy, 'testRangeSelectionConfig');
557
558         var anomalyDetectionStrategies = this.get('anomalyDetectionStrategies').filterBy('enabled');
559         var result = this._computeMovingAverageAndOutliers(chartData, movingAverageStrategy, envelopingStrategy, testRangeSelectionStrategy, anomalyDetectionStrategies);
560         if (!result)
561             return;
562
563         chartData.movingAverage = result.movingAverage;
564         this.set('highlightedItems', result.anomalies);
565         var currentTimeSeriesData = chartData.current.series();
566         this.set('testRangeCandidates', result.testRangeCandidates.map(function (range) {
567             return Ember.Object.create({
568                 startRun: currentTimeSeriesData[range[0]].measurement.id(),
569                 endRun: currentTimeSeriesData[range[1]].measurement.id(),
570                 status: 'testingRange',
571             });
572         }));
573     },
574     _movingAverageOrEnvelopeStrategyDidChange: function () {
575         var chartData = this.get('chartData');
576         if (!chartData)
577             return;
578         this._setNewChartData(chartData);
579     }.observes('chosenMovingAverageStrategy', 'chosenMovingAverageStrategy.parameterList.@each.value',
580         'chosenEnvelopingStrategy', 'chosenEnvelopingStrategy.parameterList.@each.value',
581         'chosenTestRangeSelectionStrategy', 'chosenTestRangeSelectionStrategy.parameterList.@each.value',
582         'anomalyDetectionStrategies.@each.enabled'),
583     _computeMovingAverageAndOutliers: function (chartData, movingAverageStrategy, envelopingStrategy, testRangeSelectionStrategy, anomalyDetectionStrategies)
584     {
585         var currentTimeSeriesData = chartData.current.series();
586         var movingAverageIsSetByUser = movingAverageStrategy && movingAverageStrategy.execute;
587         var movingAverageValues = this._executeStrategy(
588             movingAverageIsSetByUser ? movingAverageStrategy : Statistics.MovingAverageStrategies[0], currentTimeSeriesData);
589         if (!movingAverageValues)
590             return null;
591
592         var testRangeCandidates = [];
593         if (movingAverageStrategy && movingAverageStrategy.isSegmentation && testRangeSelectionStrategy && testRangeSelectionStrategy.execute)
594             testRangeCandidates = this._executeStrategy(testRangeSelectionStrategy, currentTimeSeriesData, [movingAverageValues]);
595
596         var envelopeIsSetByUser = envelopingStrategy && envelopingStrategy.execute;
597         var envelopeDelta = this._executeStrategy(envelopeIsSetByUser ? envelopingStrategy : Statistics.EnvelopingStrategies[0],
598             currentTimeSeriesData, [movingAverageValues]);
599
600         for (var i = 0; i < currentTimeSeriesData.length; i++) {
601             var currentValue = currentTimeSeriesData[i].value;
602             var movingAverageValue = movingAverageValues[i];
603             if (currentValue < movingAverageValue - envelopeDelta || movingAverageValue + envelopeDelta < currentValue)
604                 currentTimeSeriesData[i].isOutlier = true;
605         }
606         if (!envelopeIsSetByUser)
607             envelopeDelta = null;
608
609         var anomalies = {};
610         if (anomalyDetectionStrategies.length) {
611             var isAnomalyArray = new Array(currentTimeSeriesData.length);
612             for (var strategy of anomalyDetectionStrategies) {
613                 var anomalyLengths = this._executeStrategy(strategy, currentTimeSeriesData, [movingAverageValues, envelopeDelta]);
614                 for (var i = 0; i < currentTimeSeriesData.length; i++)
615                     isAnomalyArray[i] = isAnomalyArray[i] || anomalyLengths[i];
616             }
617             for (var i = 0; i < isAnomalyArray.length; i++) {
618                 if (!isAnomalyArray[i])
619                     continue;
620                 anomalies[currentTimeSeriesData[i].measurement.id()] = true;
621                 while (isAnomalyArray[i] && i < isAnomalyArray.length)
622                     ++i;
623             }
624         }
625
626         var movingAverageTimeSeries = null;
627         if (movingAverageIsSetByUser) {
628             movingAverageTimeSeries = new TimeSeries(currentTimeSeriesData.map(function (point, index) {
629                 var value = movingAverageValues[index];
630                 return {
631                     measurement: point.measurement,
632                     time: point.time,
633                     value: value,
634                     interval: envelopeDelta !== null ? [value - envelopeDelta, value + envelopeDelta] : null,
635                 }
636             }));
637         }
638
639         return {
640             movingAverage: movingAverageTimeSeries,
641             anomalies: anomalies,
642             testRangeCandidates: testRangeCandidates,
643         };
644     },
645     _executeStrategy: function (strategy, currentTimeSeriesData, additionalArguments)
646     {
647         var parameters = (strategy.parameterList || []).map(function (param) {
648             var parsed = parseFloat(param.value);
649             return Math.min(param.max || Infinity, Math.max(param.min || -Infinity, isNaN(parsed) ? 0 : parsed));
650         });
651         parameters.push(currentTimeSeriesData.map(function (point) { return point.value }));
652         return strategy.execute.apply(window, parameters.concat(additionalArguments));
653     },
654     _updateStrategyConfigIfNeeded: function (strategy, configName)
655     {
656         var config = null;
657         if (strategy && strategy.execute)
658             config = [strategy.id].concat((strategy.parameterList || []).map(function (param) { return param.value; }));
659
660         if (JSON.stringify(config) != JSON.stringify(this.get(configName)))
661             this.set(configName, config);
662     },
663     _updateDetails: function ()
664     {
665         var selectedPoints = this.get('selectedPoints');
666         var currentPoint = this.get('hoveredOrSelectedItem');
667         if (!selectedPoints && !currentPoint) {
668             this.set('details', null);
669             return;
670         }
671
672         var currentMeasurement;
673         var previousPoint;
674         if (!selectedPoints)
675             previousPoint = currentPoint.series.previousPoint(currentPoint);
676         else {
677             currentPoint = selectedPoints[selectedPoints.length - 1];
678             previousPoint = selectedPoints[0];
679         }
680         var currentMeasurement = currentPoint.measurement;
681         var oldMeasurement = previousPoint ? previousPoint.measurement : null;
682
683         var formattedRevisions = currentMeasurement.formattedRevisions(oldMeasurement);
684         var revisions = App.Manifest.get('repositories')
685             .filter(function (repository) { return formattedRevisions[repository.get('id')]; })
686             .map(function (repository) {
687             var revision = Ember.Object.create(formattedRevisions[repository.get('id')]);
688             revision['url'] = revision.previousRevision
689                 ? repository.urlForRevisionRange(revision.previousRevision, revision.currentRevision)
690                 : repository.urlForRevision(revision.currentRevision);
691             revision['name'] = repository.get('name');
692             revision['repository'] = repository;
693             return revision; 
694         });
695
696         var buildNumber = null;
697         var buildURL = null;
698         if (!selectedPoints) {
699             buildNumber = currentMeasurement.buildNumber();
700             var builder = App.Manifest.builder(currentMeasurement.builderId());
701             if (builder)
702                 buildURL = builder.urlFromBuildNumber(buildNumber);
703         }
704
705         this.set('details', Ember.Object.create({
706             status: this.computeStatus(currentPoint, previousPoint),
707             buildNumber: buildNumber,
708             buildURL: buildURL,
709             buildTime: currentMeasurement.formattedBuildTime(),
710             revisions: revisions,
711         }));
712     }.observes('hoveredOrSelectedItem', 'selectedPoints'),
713 });
714
715 App.encodePrettifiedJSON = function (plain)
716 {
717     function numberIfPossible(string) {
718         return string == parseInt(string) ? parseInt(string) : string;
719     }
720
721     function recursivelyConvertNumberIfPossible(input) {
722         if (input instanceof Array) {
723             return input.map(recursivelyConvertNumberIfPossible);
724         }
725         return numberIfPossible(input);
726     }
727
728     return JSON.stringify(recursivelyConvertNumberIfPossible(plain))
729         .replace(/\[/g, '(').replace(/\]/g, ')').replace(/\,/g, '-');
730 }
731
732 App.decodePrettifiedJSON = function (encoded)
733 {
734     var parsed = encoded.replace(/\(/g, '[').replace(/\)/g, ']').replace(/\-/g, ',');
735     try {
736         return JSON.parse(parsed);
737     } catch (exception) {
738         return null;
739     }
740 }
741
742 App.ChartsController = Ember.Controller.extend({
743     queryParams: ['paneList', 'zoom', 'since'],
744     needs: ['pane'],
745     _currentEncodedPaneList: null,
746     panes: [],
747     platforms: null,
748     sharedZoom: null,
749     startTime: null,
750     present: Date.now(),
751     defaultSince: Date.now() - 7 * 24 * 3600 * 1000,
752
753     addPane: function (pane)
754     {
755         this.panes.unshiftObject(pane);
756     },
757
758     removePane: function (pane)
759     {
760         this.panes.removeObject(pane);
761     },
762
763     refreshPanes: function()
764     {
765         var paneList = this.get('paneList');
766         if (paneList === this._currentEncodedPaneList)
767             return;
768
769         var panes = this._parsePaneList(paneList || '[]');
770         if (!panes) {
771             console.log('Failed to parse', jsonPaneList, exception);
772             return;
773         }
774         this.set('panes', panes);
775         this._currentEncodedPaneList = paneList;
776     }.observes('paneList').on('init'),
777
778     refreshZoom: function()
779     {
780         var zoom = this.get('zoom');
781         if (!zoom) {
782             this.set('sharedZoom', null);
783             return;
784         }
785
786         zoom = zoom.split('-');
787         var selection = new Array(2);
788         try {
789             selection[0] = new Date(parseFloat(zoom[0]));
790             selection[1] = new Date(parseFloat(zoom[1]));
791         } catch (error) {
792             console.log('Failed to parse the zoom', zoom);
793         }
794         this.set('sharedZoom', selection);
795
796         var startTime = this.get('startTime');
797         if (startTime && startTime > selection[0])
798             this.set('startTime', selection[0]);
799
800     }.observes('zoom').on('init'),
801
802     _startTimeChanged: function () {
803         this.set('sharedDomain', [this.get('startTime'), this.get('present')]);
804         this._scheduleQueryStringUpdate();
805     }.observes('startTime'),
806
807     _sinceChanged: function () {
808         var since = parseInt(this.get('since'));
809         if (isNaN(since))
810             since = this.defaultSince;
811         this.set('startTime', new Date(since));
812     }.observes('since').on('init'),
813
814     _parsePaneList: function (encodedPaneList)
815     {
816         var parsedPaneList = App.decodePrettifiedJSON(encodedPaneList);
817         if (!parsedPaneList)
818             return null;
819
820         // FIXME: Don't re-create all panes.
821         var self = this;
822         return parsedPaneList.map(function (paneInfo) {
823             var timeRange = null;
824             var selectedItem = null;
825             if (paneInfo[2] instanceof Array) {
826                 var timeRange = paneInfo[2];
827                 try {
828                     timeRange = [new Date(timeRange[0]), new Date(timeRange[1])];
829                 } catch (error) {
830                     console.log("Failed to parse the time range:", timeRange, error);
831                 }
832             } else
833                 selectedItem = paneInfo[2];
834
835             return App.Pane.create({
836                 store: self.store,
837                 info: paneInfo,
838                 platformId: paneInfo[0],
839                 metricId: paneInfo[1],
840                 selectedItem: selectedItem,
841                 timeRange: timeRange,
842                 showFullYAxis: paneInfo[3],
843                 movingAverageConfig: paneInfo[4],
844                 envelopingConfig: paneInfo[5],
845                 testRangeSelectionConfig: paneInfo[6],
846             });
847         });
848     },
849
850     _serializePaneList: function (panes)
851     {
852         if (!panes.length)
853             return undefined;
854         var self = this;
855         return App.encodePrettifiedJSON(panes.map(function (pane) {
856             return [
857                 pane.get('platformId'),
858                 pane.get('metricId'),
859                 pane.get('timeRange') ? pane.get('timeRange').map(function (date) { return date.getTime() }) : pane.get('selectedItem'),
860                 pane.get('showFullYAxis'),
861                 pane.get('movingAverageConfig'),
862                 pane.get('envelopingConfig'),
863                 pane.get('testRangeSelectionConfig'),
864             ];
865         }));
866     },
867
868     _scheduleQueryStringUpdate: function ()
869     {
870         Ember.run.debounce(this, '_updateQueryString', 1000);
871     }.observes('sharedZoom', 'panes.@each.platform', 'panes.@each.metric', 'panes.@each.selectedItem', 'panes.@each.timeRange',
872         'panes.@each.showFullYAxis', 'panes.@each.movingAverageConfig', 'panes.@each.envelopingConfig', 'panes.@each.testRangeSelectionConfig'),
873
874     _updateQueryString: function ()
875     {
876         this._currentEncodedPaneList = this._serializePaneList(this.get('panes'));
877         this.set('paneList', this._currentEncodedPaneList);
878
879         var zoom = undefined;
880         var sharedZoom = this.get('sharedZoom');
881         if (sharedZoom && !App.domainsAreEqual(sharedZoom, this.get('sharedDomain')))
882             zoom = +sharedZoom[0] + '-' + +sharedZoom[1];
883         this.set('zoom', zoom);
884
885         if (this.get('startTime') - this.defaultSince)
886             this.set('since', this.get('startTime') - 0);
887     },
888
889     actions: {
890         addPaneByMetricAndPlatform: function (param)
891         {
892             this.addPane(App.Pane.create({
893                 store: this.store,
894                 platformId: param.platform.get('id'),
895                 metricId: param.metric.get('id'),
896                 showingDetails: false
897             }));
898         },
899     },
900
901     init: function ()
902     {
903         this._super();
904         var self = this;
905         App.buildPopup(this.store, 'addPaneByMetricAndPlatform').then(function (platforms) {
906             self.set('platforms', platforms);
907         });
908     },
909 });
910
911 App.buildPopup = function(store, action, position)
912 {
913     return App.Manifest.fetch(store).then(function () {
914         return App.Manifest.get('platforms').sortBy('label').map(function (platform) {
915             return App.PlatformProxyForPopup.create({content: platform,
916                 action: action, position: position});
917         });
918     });
919 }
920
921 App.PlatformProxyForPopup = Ember.ObjectProxy.extend({
922     children: function ()
923     {
924         var platform = this.content;
925         var containsTest = this.content.containsTest.bind(this.content);
926         var action = this.get('action');
927         var position = this.get('position');
928         return App.Manifest.get('topLevelTests')
929             .filter(containsTest)
930             .map(function (test) {
931                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
932             });
933     }.property('App.Manifest.topLevelTests'),
934 });
935
936 App.TestProxyForPopup = Ember.ObjectProxy.extend({
937     platform: null,
938     children: function ()
939     {
940         var platform = this.get('platform');
941         var action = this.get('action');
942         var position = this.get('position');
943
944         var childTests = this.get('childTests')
945             .filter(function (test) { return platform.containsTest(test); })
946             .map(function (test) {
947                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
948             });
949
950         var metrics = this.get('metrics')
951             .filter(function (metric) { return platform.containsMetric(metric); })
952             .map(function (metric) {
953                 var aggregator = metric.get('aggregator');
954                 return {
955                     actionName: action,
956                     actionArgument: {platform: platform, metric: metric, position:position},
957                     label: metric.get('label')
958                 };
959             });
960
961         if (childTests.length && metrics.length)
962             metrics.push({isSeparator: true});
963
964         return metrics.concat(childTests);
965     }.property('childTests', 'metrics'),
966 });
967
968 App.domainsAreEqual = function (domain1, domain2) {
969     return (!domain1 && !domain2) || (domain1 && domain2 && !(domain1[0] - domain2[0]) && !(domain1[1] - domain2[1]));
970 }
971
972 App.PaneController = Ember.ObjectController.extend({
973     needs: ['charts'],
974     sharedTime: Ember.computed.alias('parentController.sharedTime'),
975     sharedSelection: Ember.computed.alias('parentController.sharedSelection'),
976     selection: null,
977     actions: {
978         toggleDetails: function()
979         {
980             this.toggleProperty('showingDetails');
981         },
982         close: function ()
983         {
984             this.parentController.removePane(this.get('model'));
985         },
986         toggleBugsPane: function ()
987         {
988             if (this.toggleProperty('showingAnalysisPane')) {
989                 this.set('showingSearchPane', false);
990                 this.set('showingStatPane', false);
991             }
992         },
993         toggleShowOutlier: function ()
994         {
995             var pane = this.get('model');
996             pane.toggleProperty('showOutlier');
997             var chartData = pane.get('chartData');
998             if (!chartData)
999                 return;
1000             pane._setNewChartData(chartData);
1001         },
1002         createAnalysisTask: function ()
1003         {
1004             var name = this.get('newAnalysisTaskName');
1005             var points = this.get('selectedPoints');
1006             Ember.assert('The analysis name should not be empty', name);
1007             Ember.assert('There should be at least two points in the range', points && points.length >= 2);
1008
1009             var newWindow = window.open();
1010             var self = this;
1011             App.AnalysisTask.create(name, points[0].measurement, points[points.length - 1].measurement).then(function (data) {
1012                 // FIXME: Update the UI to show the new analysis task.
1013                 var url = App.Router.router.generate('analysisTask', data['taskId']);
1014                 newWindow.location.href = '#' + url;
1015                 self.get('model').fetchAnalyticRanges();
1016             }, function (error) {
1017                 newWindow.close();
1018                 if (error === 'DuplicateAnalysisTask') {
1019                     // FIXME: Duplicate this error more gracefully.
1020                 }
1021                 alert(error);
1022             });
1023         },
1024         toggleSearchPane: function ()
1025         {
1026             if (!App.Manifest.repositoriesWithReportedCommits)
1027                 return;
1028             var model = this.get('model');
1029             if (!model.get('commitSearchRepository'))
1030                 model.set('commitSearchRepository', App.Manifest.repositoriesWithReportedCommits[0]);
1031             if (this.toggleProperty('showingSearchPane')) {
1032                 this.set('showingAnalysisPane', false);
1033                 this.set('showingStatPane', false);
1034             }
1035         },
1036         searchCommit: function () {
1037             var model = this.get('model');
1038             model.searchCommit(model.get('commitSearchRepository'), model.get('commitSearchKeyword'));                
1039         },
1040         toggleStatPane: function ()
1041         {
1042             if (this.toggleProperty('showingStatPane')) {
1043                 this.set('showingSearchPane', false);
1044                 this.set('showingAnalysisPane', false);
1045             }
1046         },
1047         zoomed: function (selection)
1048         {
1049             this.set('mainPlotDomain', selection ? selection : this.get('overviewDomain'));
1050             if (selection)
1051                 this.set('overviewSelection', selection);
1052             Ember.run.debounce(this, 'propagateZoom', 100);
1053         },
1054     },
1055     _overviewSelectionChanged: function ()
1056     {
1057         var overviewSelection = this.get('overviewSelection');
1058         if (App.domainsAreEqual(overviewSelection, this.get('mainPlotDomain')))
1059             return;
1060         this.set('mainPlotDomain', overviewSelection || this.get('overviewDomain'));
1061         Ember.run.debounce(this, 'propagateZoom', 100);
1062     }.observes('overviewSelection'),
1063     _sharedDomainChanged: function ()
1064     {
1065         var newDomain = this.get('parentController').get('sharedDomain');
1066         if (App.domainsAreEqual(newDomain, this.get('overviewDomain')))
1067             return;
1068         this.set('overviewDomain', newDomain);
1069         if (!this.get('overviewSelection'))
1070             this.set('mainPlotDomain', newDomain);
1071     }.observes('parentController.sharedDomain').on('init'),
1072     propagateZoom: function ()
1073     {
1074         this.get('parentController').set('sharedZoom', this.get('mainPlotDomain'));
1075     },
1076     _sharedZoomChanged: function ()
1077     {
1078         var newSelection = this.get('parentController').get('sharedZoom');
1079         if (App.domainsAreEqual(newSelection, this.get('mainPlotDomain')))
1080             return;
1081         this.set('mainPlotDomain', newSelection || this.get('overviewDomain'));
1082         this.set('overviewSelection', newSelection);
1083     }.observes('parentController.sharedZoom').on('init'),
1084     _updateCanAnalyze: function ()
1085     {
1086         var pane = this.get('model');
1087         var points = pane.get('selectedPoints');
1088         this.set('cannotAnalyze', !this.get('newAnalysisTaskName') || !points || points.length < 2);
1089         this.set('cannotMarkOutlier', !!points || !this.get('selectedItem'));
1090
1091         var selectedMeasurement = this.selectedMeasurement();
1092         this.set('selectedItemIsMarkedOutlier', selectedMeasurement && selectedMeasurement.markedOutlier());
1093
1094     }.observes('newAnalysisTaskName', 'model.selectedPoints', 'model.selectedItem').on('init'),
1095     selectedMeasurement: function () {
1096         var chartData = this.get('model').get('chartData');
1097         var selectedItem = this.get('selectedItem');
1098         if (!chartData || !selectedItem)
1099             return null;
1100         var point = chartData.current.findPointByMeasurementId(selectedItem);
1101         Ember.assert('selectedItem should always be in the current chart data', point);
1102         return point.measurement;
1103     },
1104     showOutlierTitle: function ()
1105     {
1106         return this.get('showOutlier') ? 'Hide outliers' : 'Show outliers';
1107     }.property('showOutlier'),
1108     _selectedItemIsMarkedOutlierDidChange: function ()
1109     {
1110         var selectedMeasurement = this.selectedMeasurement();
1111         if (!selectedMeasurement)
1112             return;
1113         var selectedItemIsMarkedOutlier = this.get('selectedItemIsMarkedOutlier');
1114         if (selectedMeasurement.markedOutlier() == selectedItemIsMarkedOutlier)
1115             return;
1116         var pane = this.get('model');
1117         selectedMeasurement.setMarkedOutlier(!!selectedItemIsMarkedOutlier).then(function () {
1118             alert(selectedItemIsMarkedOutlier ? 'Marked the point as an outlier' : 'The point is no longer marked as an outlier');
1119             pane.refetchRuns();
1120         }, function (error) {
1121             alert('Failed to update the status:' + error);
1122         });
1123     }.observes('selectedItemIsMarkedOutlier'),
1124 });
1125
1126 App.AnalysisRoute = Ember.Route.extend({
1127     model: function () {
1128         return this.store.findAll('analysisTask').then(function (tasks) {
1129             return Ember.Object.create({'tasks': tasks.sortBy('createdAt').toArray().reverse()});
1130         });
1131     },
1132 });
1133
1134 App.AnalysisTaskRoute = Ember.Route.extend({
1135     model: function (param)
1136     {
1137         return this.store.find('analysisTask', param.taskId);
1138     },
1139 });
1140
1141 App.AnalysisTaskController = Ember.Controller.extend({
1142     label: Ember.computed.alias('model.name'),
1143     platform: Ember.computed.alias('model.platform'),
1144     metric: Ember.computed.alias('model.metric'),
1145     details: Ember.computed.alias('pane.details'),
1146     roots: [],
1147     bugTrackers: [],
1148     possibleRepetitionCounts: [1, 2, 3, 4, 5, 6],
1149     analysisResultOptions: [
1150         {label: 'Still in investigation', result: null},
1151         {label: 'Inconclusive', result: 'inconclusive', needed: true},
1152         {label: 'Definite progression', result: 'progression', needed: true},
1153         {label: 'Definite regression', result: 'regression', needed: true},
1154         {label: 'No change', result: 'unchanged', needsFeedback: true},
1155     ],
1156     shouldNotHaveBeenCreated: false,
1157     needsFeedback: function ()
1158     {
1159         var chosen = this.get('chosenAnalysisResult');
1160         return chosen && chosen.needsFeedback;
1161     }.property('chosenAnalysisResult'),
1162     _updateChosenAnalysisResult: function ()
1163     {
1164         var analysisTask = this.get('model');
1165         if (!analysisTask)
1166             return;
1167         var currentResult = analysisTask.get('result');
1168         for (var option of this.analysisResultOptions) {
1169             if (option.result == currentResult) {
1170                 this.set('chosenAnalysisResult', option);
1171                 break;                
1172             }
1173         }
1174     }.observes('model'),
1175     _taskUpdated: function ()
1176     {
1177         var model = this.get('model');
1178         if (!model)
1179             return;
1180
1181         App.Manifest.fetch(this.store).then(this._fetchedManifest.bind(this));
1182         this.set('pane', App.Pane.create({
1183             store: this.store,
1184             platformId: model.get('platform').get('id'),
1185             metricId: model.get('metric').get('id'),
1186         }));
1187
1188         var self = this;
1189         model.get('testGroups').then(function (groups) {
1190             self.set('testGroupPanes', groups.map(function (group) { return App.TestGroupPane.create({content: group}); }));
1191         });
1192     }.observes('model', 'model.testGroups').on('init'),
1193     _fetchedManifest: function ()
1194     {
1195         var trackerIdToBugNumber = {};
1196         this.get('model').get('bugs').forEach(function (bug) {
1197             trackerIdToBugNumber[bug.get('bugTracker').get('id')] = bug.get('number');
1198         });
1199
1200         this.set('bugTrackers', App.Manifest.get('bugTrackers').map(function (bugTracker) {
1201             var bugNumber = trackerIdToBugNumber[bugTracker.get('id')];
1202             return Ember.ObjectProxy.create({
1203                 elementId: 'bug-' + bugTracker.get('id'),
1204                 content: bugTracker,
1205                 bugNumber: bugNumber,
1206                 editedBugNumber: bugNumber,
1207             });
1208         }));
1209     },
1210     _chartDataChanged: function ()
1211     {
1212         var pane = this.get('pane');
1213         if (!pane)
1214             return;
1215
1216         var chartData = pane.get('chartData');
1217         if (!chartData)
1218             return null;
1219
1220         var currentTimeSeries = chartData.current;
1221         if (!currentTimeSeries)
1222             return null; // FIXME: Report an error.
1223
1224         var start = currentTimeSeries.findPointByMeasurementId(this.get('model').get('startRun'));
1225         var end = currentTimeSeries.findPointByMeasurementId(this.get('model').get('endRun'));
1226         if (!start || !end)
1227             return null; // FIXME: Report an error.
1228
1229         var highlightedItems = {};
1230         highlightedItems[start.measurement.id()] = true;
1231         highlightedItems[end.measurement.id()] = true;
1232
1233         var formatedPoints = currentTimeSeries.seriesBetweenPoints(start, end).map(function (point, index) {
1234             return {
1235                 id: point.measurement.id(),
1236                 measurement: point.measurement,
1237                 label: 'Point ' + (index + 1),
1238                 value: chartData.formatWithUnit(point.value),
1239             };
1240         });
1241
1242         var margin = (end.time - start.time) * 0.1;
1243         this.set('highlightedItems', highlightedItems);
1244         this.set('overviewEndPoints', [start, end]);
1245         this.set('analysisPoints', formatedPoints);
1246
1247         var overviewDomain = [start.time - margin, +end.time + margin];
1248
1249         var testGroupPanes = this.get('testGroupPanes');
1250         if (testGroupPanes) {
1251             testGroupPanes.setEach('overviewPane', pane);
1252             testGroupPanes.setEach('overviewDomain', overviewDomain);
1253         }
1254
1255         this.set('overviewDomain', overviewDomain);
1256     }.observes('pane.chartData'),
1257     updateRootConfigurations: function ()
1258     {
1259         var analysisPoints = this.get('analysisPoints');
1260         if (!analysisPoints)
1261             return;
1262         var repositoryToRevisions = {};
1263         analysisPoints.forEach(function (point, pointIndex) {
1264             var revisions = point.measurement.formattedRevisions();
1265             for (var repositoryId in revisions) {
1266                 if (!repositoryToRevisions[repositoryId])
1267                     repositoryToRevisions[repositoryId] = new Array(analysisPoints.length);
1268                 var revision = revisions[repositoryId];
1269                 repositoryToRevisions[repositoryId][pointIndex] = {
1270                     label: point.label + ': ' + revision.label,
1271                     value: revision.currentRevision,
1272                 };
1273             }
1274         });
1275
1276         var self = this;
1277         this.get('model').get('triggerable').then(function (triggerable) {
1278             if (!triggerable)
1279                 return;
1280
1281             self.set('configurations', ['A', 'B']);
1282             self.set('rootConfigurations', triggerable.get('acceptedRepositories').map(function (repository) {
1283                 var repositoryId = repository.get('id');
1284                 var options = [{label: 'None'}].concat((repositoryToRevisions[repositoryId] || []).map(function (option, index) {
1285                     if (!option || !option['value'])
1286                         return {value: '', label: analysisPoints[index].label + ': None'}; 
1287                     return option;
1288                 }));
1289                 return Ember.Object.create({
1290                     repository: repository,
1291                     name: repository.get('name'),
1292                     sets: [
1293                         Ember.Object.create({name: 'A[' + repositoryId + ']',
1294                             options: options,
1295                             selection: options[1]}),
1296                         Ember.Object.create({name: 'B[' + repositoryId + ']',
1297                             options: options,
1298                             selection: options[options.length - 1]}),
1299                     ],
1300                 });
1301             }));
1302         });
1303     }.observes('analysisPoints'),
1304     actions: {
1305         associateBug: function (bugTracker, bugNumber)
1306         {
1307             var model = this.get('model');
1308             this.store.createRecord('bug',
1309                 {task: this.get('model'), bugTracker: bugTracker.get('content'), number: bugNumber}).save().then(function () {
1310                     // FIXME: Should we notify the user?
1311                 }, function (error) {
1312                     alert('Failed to associate the bug: ' + error);
1313                 });
1314         },
1315         saveStatus: function ()
1316         {
1317             var chosenResult = this.get('chosenAnalysisResult');
1318             var analysisTask = this.get('model');
1319             analysisTask.set('result', chosenResult.result);
1320             if (chosenResult.needed)
1321                 analysisTask.set('needed', true);
1322             else if (chosenResult.needsFeedback && this.get('notNeeded'))
1323                 analysisTask.set('needed', false);
1324             else
1325                 analysisTask.set('needed', null);
1326
1327             analysisTask.saveStatus().then(function () {
1328                 alert('Saved the status');
1329             }, function (error) {
1330                 alert('Failed to save the status: ' + error);
1331             });
1332         },
1333         createTestGroup: function (name, repetitionCount)
1334         {
1335             var analysisTask = this.get('model');
1336             if (analysisTask.get('testGroups').isAny('name', name)) {
1337                 alert('Cannot create two test groups of the same name.');
1338                 return;
1339             }
1340
1341             var roots = {};
1342             var rootConfigurations = this.get('rootConfigurations').toArray();
1343             for (var root of rootConfigurations) {
1344                 var sets = root.get('sets');
1345                 var hasSelection = function (item) { return item.get('selection') && item.get('selection').value; };
1346                 if (!sets.any(hasSelection))
1347                     continue;
1348                 if (!sets.every(hasSelection)) {
1349                     alert('Only some configuration specifies ' + root.get('name'));
1350                     return;
1351                 }
1352                 roots[root.get('name')] = sets.map(function (item) { return item.get('selection').value; });                
1353             }
1354
1355             App.TestGroup.create(analysisTask, name, roots, repetitionCount).then(function () {
1356             }, function (error) {
1357                 alert('Failed to create a new test group:' + error);
1358             });
1359         },
1360         toggleShowRequestList: function (configuration)
1361         {
1362             configuration.toggleProperty('showRequestList');
1363         }
1364     },
1365     _updateRootsBySelectedPoints: function ()
1366     {
1367         var rootConfigurations = this.get('rootConfigurations');
1368         var pane = this.get('pane');
1369         if (!rootConfigurations || !pane)
1370             return;
1371
1372         var rootSetPoints;
1373         var selectedPoints = pane.get('selectedPoints');
1374         if (selectedPoints && selectedPoints.length >= 2)
1375             rootSetPoints = [selectedPoints[0], selectedPoints[selectedPoints.length - 1]];
1376         else
1377             rootSetPoints = this.get('overviewEndPoints');
1378         if (!rootSetPoints)
1379             return;
1380
1381         rootConfigurations.forEach(function (root) {
1382             root.get('sets').forEach(function (set, setIndex) {
1383                 if (setIndex >= rootSetPoints.length)
1384                     return;
1385                 var targetRevision = rootSetPoints[setIndex].measurement.revisionForRepository(root.get('repository').get('id'));
1386                 var selectedOption;
1387                 if (targetRevision)
1388                     selectedOption = set.get('options').find(function (option) { return option.value == targetRevision; });
1389                 set.set('selection', selectedOption || set.get('options')[0]);
1390             });
1391         });
1392
1393     }.observes('pane.selectedPoints'),
1394 });
1395
1396 App.TestGroupPane = Ember.ObjectProxy.extend({
1397     _populate: function ()
1398     {
1399         var buildRequests = this.get('buildRequests');
1400         var testResults = this.get('testResults');
1401         if (!buildRequests || !testResults)
1402             return [];
1403
1404         var repositories = this._computeRepositoryList();
1405         this.set('repositories', repositories);
1406
1407         var requestsByRooSet = this._groupRequestsByConfigurations(buildRequests);
1408
1409         var configurations = [];
1410         var index = 0;
1411         var range = {min: Infinity, max: -Infinity};
1412         for (var rootSetId in requestsByRooSet) {
1413             var configLetter = String.fromCharCode('A'.charCodeAt(0) + index++);
1414             configurations.push(this._createConfigurationSummary(requestsByRooSet[rootSetId], configLetter, range));
1415         }
1416
1417         var margin = 0.1 * (range.max - range.min);
1418         range.max += margin;
1419         range.min -= margin;
1420
1421         this.set('configurations', configurations);
1422
1423         var comparisons = [];
1424         for (var i = 0; i < configurations.length - 1; i++) {
1425             var summary1 = configurations[i].summary;
1426             for (var j = i + 1; j < configurations.length; j++) {
1427                 var summary2 = configurations[j].summary;
1428                 comparisons.push({
1429                     label: summary1.configLetter + ' / ' + summary2.configLetter,
1430                     result: this._computeStatisticalSignificance(summary1.measuredValues, summary2.measuredValues)
1431                 });
1432             }
1433         }
1434         this.set('comparisons', comparisons);
1435     }.observes('testResults', 'buildRequests'),
1436     _computeStatisticalSignificance: function (values1, values2)
1437     {
1438         var tFormatter = d3.format('.3g');
1439         var probabilityFormatter = d3.format('.2p');
1440         var statistics = Statistics.probabilityRangeForWelchsT(values1, values2);
1441         if (isNaN(statistics.t) || isNaN(statistics.degreesOfFreedom))
1442             return 'N/A';
1443
1444         var details = ' (t=' + tFormatter(statistics.t) + ' df=' + tFormatter(statistics.degreesOfFreedom) + ')';
1445
1446         if (!statistics.range[0])
1447             return 'Not statistically significant' + details;
1448
1449         var lowerLimit = probabilityFormatter(statistics.range[0]);
1450         if (!statistics.range[1])
1451             return 'Statistical significance > ' + lowerLimit + details;
1452
1453         return lowerLimit + ' < Statistical significance < ' + probabilityFormatter(statistics.range[1]) + details;
1454     },
1455     _updateReferenceChart: function ()
1456     {
1457         var configurations = this.get('configurations');
1458         var chartData = this.get('overviewPane') ? this.get('overviewPane').get('chartData') : null;
1459         if (!configurations || !chartData || this.get('referenceChart'))
1460             return;
1461
1462         var currentTimeSeries = chartData.current;
1463         if (!currentTimeSeries)
1464             return;
1465
1466         var repositories = this.get('repositories');
1467         var highlightedItems = {};
1468         var failedToFindPoint = false;
1469         configurations.forEach(function (config) {
1470             var revisions = {};
1471             config.get('rootSet').get('roots').forEach(function (root) {
1472                 revisions[root.get('repository').get('id')] = root.get('revision');
1473             });
1474             var point = currentTimeSeries.findPointByRevisions(revisions);
1475             if (!point) {
1476                 failedToFindPoint = true;
1477                 return;
1478             }
1479             highlightedItems[point.measurement.id()] = true;
1480         });
1481         if (failedToFindPoint)
1482             return;
1483
1484         this.set('referenceChart', {
1485             data: chartData,
1486             highlightedItems: highlightedItems,
1487         });
1488     }.observes('configurations', 'overviewPane.chartData'),
1489     _computeRepositoryList: function ()
1490     {
1491         var specifiedRepositories = new Ember.Set();
1492         (this.get('rootSets') || []).forEach(function (rootSet) {
1493             (rootSet.get('roots') || []).forEach(function (root) {
1494                 specifiedRepositories.add(root.get('repository'));
1495             });
1496         });
1497         var reportedRepositories = new Ember.Set();
1498         var testResults = this.get('testResults');
1499         (this.get('buildRequests') || []).forEach(function (request) {
1500             var point = testResults.current.findPointByBuild(request.get('build'));
1501             if (!point)
1502                 return;
1503
1504             var revisionByRepositoryId = point.measurement.formattedRevisions();
1505             for (var repositoryId in revisionByRepositoryId) {
1506                 var repository = App.Manifest.repository(repositoryId);
1507                 if (!specifiedRepositories.contains(repository))
1508                     reportedRepositories.add(repository);
1509             }
1510         });
1511         return specifiedRepositories.sortBy('name').concat(reportedRepositories.sortBy('name'));
1512     },
1513     _groupRequestsByConfigurations: function (requests, repositoryList)
1514     {
1515         var rootSetIdToRequests = {};
1516         var testGroup = this;
1517         requests.forEach(function (request) {
1518             var rootSetId = request.get('rootSet').get('id');
1519             if (!rootSetIdToRequests[rootSetId])
1520                 rootSetIdToRequests[rootSetId] = [];
1521             rootSetIdToRequests[rootSetId].push(request);
1522         });
1523         return rootSetIdToRequests;
1524     },
1525     _createConfigurationSummary: function (buildRequests, configLetter, range)
1526     {
1527         var repositories = this.get('repositories');
1528         var testResults = this.get('testResults');
1529         var requests = buildRequests.map(function (originalRequest) {
1530             var point = testResults.current.findPointByBuild(originalRequest.get('build'));
1531             var revisionByRepositoryId = point ? point.measurement.formattedRevisions() : {};
1532             return Ember.ObjectProxy.create({
1533                 content: originalRequest,
1534                 revisionList: repositories.map(function (repository, index) {
1535                     return (revisionByRepositoryId[repository.get('id')] || {label:null}).label;
1536                 }),
1537                 value: point ? point.value : null,
1538                 valueRange: range,
1539                 formattedValue: point ? testResults.formatWithUnit(point.value) : null,
1540                 buildLabel: point ? 'Build ' + point.measurement.buildNumber() : null,
1541             });
1542         });
1543
1544         var rootSet = requests ? requests[0].get('rootSet') : null;
1545         var summaryRevisions = repositories.map(function (repository, index) {
1546             var revision = rootSet ? rootSet.revisionForRepository(repository) : null;
1547             if (!revision)
1548                 return requests[0].get('revisionList')[index];
1549             return Measurement.formatRevisionRange(revision).label;
1550         });
1551
1552         requests.forEach(function (request) {
1553             var revisionList = request.get('revisionList');
1554             repositories.forEach(function (repository, index) {
1555                 if (revisionList[index] == summaryRevisions[index])
1556                     revisionList[index] = null;
1557             });
1558         });
1559
1560         var valuesInConfig = requests.mapBy('value').filter(function (value) { return typeof(value) === 'number' && !isNaN(value); });
1561         var sum = Statistics.sum(valuesInConfig);
1562         var ciDelta = Statistics.confidenceIntervalDelta(0.95, valuesInConfig.length, sum, Statistics.squareSum(valuesInConfig));
1563         var mean = sum / valuesInConfig.length;
1564
1565         range.min = Math.min(range.min, Statistics.min(valuesInConfig));
1566         range.max = Math.max(range.max, Statistics.max(valuesInConfig));
1567         if (ciDelta && !isNaN(ciDelta)) {
1568             range.min = Math.min(range.min, mean - ciDelta);
1569             range.max = Math.max(range.max, mean + ciDelta);
1570         }
1571
1572         var summary = Ember.Object.create({
1573             isAverage: true,
1574             configLetter: configLetter,
1575             revisionList: summaryRevisions,
1576             formattedValue: isNaN(mean) ? null : testResults.formatWithDeltaAndUnit(mean, ciDelta),
1577             value: mean,
1578             measuredValues: valuesInConfig,
1579             confidenceIntervalDelta: ciDelta,
1580             valueRange: range,
1581             statusLabel: App.BuildRequest.aggregateStatuses(requests),
1582         });
1583
1584         return Ember.Object.create({summary: summary, requests: requests, rootSet: rootSet});
1585     },
1586 });
1587
1588 App.BoxPlotComponent = Ember.Component.extend({
1589     classNames: ['box-plot'],
1590     range: null,
1591     value: null,
1592     delta: null,
1593     didInsertElement: function ()
1594     {
1595         var element = this.get('element');
1596         var svg = d3.select(element).append('svg')
1597             .attr('viewBox', '0 0 100 20')
1598             .attr('preserveAspectRatio', 'none')
1599             .style({width: '100%', height: '100%'});
1600
1601         this._percentageRect = svg
1602             .append('rect')
1603             .attr('x', 0)
1604             .attr('y', 0)
1605             .attr('width', 0)
1606             .attr('height', 20)
1607             .attr('class', 'percentage');
1608
1609         this._deltaRect = svg
1610             .append('rect')
1611             .attr('x', 0)
1612             .attr('y', 5)
1613             .attr('width', 0)
1614             .attr('height', 10)
1615             .attr('class', 'delta')
1616             .attr('opacity', 0.5)
1617         this._updateBars();
1618     },
1619     _updateBars: function ()
1620     {
1621         if (!this._percentageRect || typeof(this._percentage) !== 'number' || isNaN(this._percentage))
1622             return;
1623
1624         this._percentageRect.attr('width', this._percentage);
1625         if (typeof(this._delta) === 'number' && !isNaN(this._delta)) {
1626             this._deltaRect.attr('x', this._percentage - this._delta);
1627             this._deltaRect.attr('width', this._delta * 2);
1628         }
1629     },
1630     valueChanged: function ()
1631     {
1632         var range = this.get('range');
1633         var value = this.get('value');
1634         if (!range || !value)
1635             return;
1636         var scalingFactor = 100 / (range.max - range.min);
1637         var percentage = (value - range.min) * scalingFactor;
1638         this._percentage = percentage;
1639         this._delta = this.get('delta') * scalingFactor;
1640         this._updateBars();
1641     }.observes('value', 'range').on('init'),
1642 });