The results of A/B testing should state statistical significance
[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, false]]);
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     _isValidId: function (id)
429     {
430         if (typeof(id) == "number")
431             return true;
432         if (typeof(id) == "string")
433             return !!id.match(/^[A-Za-z0-9_]+$/);
434         return false;
435     },
436     computeStatus: function (currentPoint, previousPoint)
437     {
438         var chartData = this.get('chartData');
439         var diffFromBaseline = this._relativeDifferentToLaterPointInTimeSeries(currentPoint, chartData.baseline);
440         var diffFromTarget = this._relativeDifferentToLaterPointInTimeSeries(currentPoint, chartData.target);
441
442         var label = '';
443         var className = '';
444         var formatter = d3.format('.3p');
445
446         var smallerIsBetter = chartData.smallerIsBetter;
447         if (diffFromBaseline !== undefined && diffFromBaseline > 0 == smallerIsBetter) {
448             label = formatter(Math.abs(diffFromBaseline)) + ' ' + (smallerIsBetter ? 'above' : 'below') + ' baseline';
449             className = 'worse';
450         } else if (diffFromTarget !== undefined && diffFromTarget < 0 == smallerIsBetter) {
451             label = formatter(Math.abs(diffFromTarget)) + ' ' + (smallerIsBetter ? 'below' : 'above') + ' target';
452             className = 'better';
453         } else if (diffFromTarget !== undefined)
454             label = formatter(Math.abs(diffFromTarget)) + ' until target';
455
456         var valueDelta = null;
457         var relativeDelta = null;
458         if (previousPoint) {
459             valueDelta = chartData.deltaFormatter(currentPoint.value - previousPoint.value);
460             relativeDelta = d3.format('+.2p')((currentPoint.value - previousPoint.value) / previousPoint.value);
461         }
462         return {
463             className: className,
464             label: label,
465             currentValue: chartData.formatter(currentPoint.value),
466             valueDelta: valueDelta,
467             relativeDelta: relativeDelta,
468         };
469     },
470     _relativeDifferentToLaterPointInTimeSeries: function (currentPoint, timeSeries)
471     {
472         if (!currentPoint || !timeSeries)
473             return undefined;
474
475         var referencePoint = timeSeries.findPointAfterTime(currentPoint.time);
476         if (!referencePoint)
477             return undefined;
478
479         return (currentPoint.value - referencePoint.value) / referencePoint.value;
480     },
481     latestStatus: function ()
482     {
483         var chartData = this.get('chartData');
484         if (!chartData || !chartData.current)
485             return null;
486
487         var lastPoint = chartData.current.lastPoint();
488         if (!lastPoint)
489             return null;
490
491         return this.computeStatus(lastPoint, chartData.current.previousPoint(lastPoint));
492     }.property('chartData'),
493     updateStatisticsTools: function ()
494     {
495         var movingAverageStrategies = Statistics.MovingAverageStrategies.map(this._cloneStrategy.bind(this));
496         this.set('movingAverageStrategies', [{label: 'None'}].concat(movingAverageStrategies));
497         this.set('chosenMovingAverageStrategy', this._configureStrategy(movingAverageStrategies, this.get('movingAverageConfig')));
498
499         var envelopingStrategies = Statistics.EnvelopingStrategies.map(this._cloneStrategy.bind(this));
500         this.set('envelopingStrategies', [{label: 'None'}].concat(envelopingStrategies));
501         this.set('chosenEnvelopingStrategy', this._configureStrategy(envelopingStrategies, this.get('envelopingConfig')));
502
503         var anomalyDetectionStrategies = Statistics.AnomalyDetectionStrategy.map(this._cloneStrategy.bind(this));
504         this.set('anomalyDetectionStrategies', anomalyDetectionStrategies);
505     }.on('init'),
506     _cloneStrategy: function (strategy)
507     {
508         var parameterList = (strategy.parameterList || []).map(function (param) { return Ember.Object.create(param); });
509         return Ember.Object.create({
510             id: strategy.id,
511             label: strategy.label,
512             description: strategy.description,
513             parameterList: parameterList,
514             execute: strategy.execute,
515         });
516     },
517     _configureStrategy: function (strategies, config)
518     {
519         if (!config || !config[0])
520             return null;
521
522         var id = config[0];
523         var chosenStrategy = strategies.find(function (strategy) { return strategy.id == id });
524         if (!chosenStrategy)
525             return null;
526
527         if (chosenStrategy.parameterList) {
528             for (var i = 0; i < chosenStrategy.parameterList.length; i++)
529                 chosenStrategy.parameterList[i].value = parseFloat(config[i + 1]);
530         }
531
532         return chosenStrategy;
533     },
534     _updateMovingAverageAndEnvelope: function ()
535     {
536         var chartData = this.get('chartData');
537         if (!chartData)
538             return;
539
540         var movingAverageStrategy = this.get('chosenMovingAverageStrategy');
541         this._updateStrategyConfigIfNeeded(movingAverageStrategy, 'movingAverageConfig');
542
543         var envelopingStrategy = this.get('chosenEnvelopingStrategy');
544         this._updateStrategyConfigIfNeeded(envelopingStrategy, 'envelopingConfig');
545         
546         var anomalyDetectionStrategies = this.get('anomalyDetectionStrategies').filterBy('enabled');
547         var anomalies = {};
548         chartData.movingAverage = this._computeMovingAverageAndOutliers(chartData, movingAverageStrategy, envelopingStrategy, anomalyDetectionStrategies, anomalies);
549         this.set('highlightedItems', anomalies);
550     },
551     _movingAverageOrEnvelopeStrategyDidChange: function () {
552         var chartData = this.get('chartData');
553         if (!chartData)
554             return;
555         this._setNewChartData(chartData);
556     }.observes('chosenMovingAverageStrategy', 'chosenMovingAverageStrategy.parameterList.@each.value',
557         'chosenEnvelopingStrategy', 'chosenEnvelopingStrategy.parameterList.@each.value',
558         'anomalyDetectionStrategies.@each.enabled'),
559     _computeMovingAverageAndOutliers: function (chartData, movingAverageStrategy, envelopingStrategy, anomalyDetectionStrategies, anomalies)
560     {
561         var currentTimeSeriesData = chartData.current.series();
562         var movingAverageIsSetByUser = movingAverageStrategy && movingAverageStrategy.execute;
563         var movingAverageValues = this._executeStrategy(
564             movingAverageIsSetByUser ? movingAverageStrategy : Statistics.MovingAverageStrategies[0], currentTimeSeriesData);
565         if (!movingAverageValues)
566             return null;
567
568         var envelopeIsSetByUser = envelopingStrategy && envelopingStrategy.execute;
569         var envelopeDelta = this._executeStrategy(envelopeIsSetByUser ? envelopingStrategy : Statistics.EnvelopingStrategies[0],
570             currentTimeSeriesData, [movingAverageValues]);
571
572         for (var i = 0; i < currentTimeSeriesData.length; i++) {
573             var currentValue = currentTimeSeriesData[i].value;
574             var movingAverageValue = movingAverageValues[i];
575             if (currentValue < movingAverageValue - envelopeDelta || movingAverageValue + envelopeDelta < currentValue)
576                 currentTimeSeriesData[i].isOutlier = true;
577         }
578         if (!envelopeIsSetByUser)
579             envelopeDelta = null;
580
581         var isAnomalyArray = new Array(currentTimeSeriesData.length);
582         for (var strategy of anomalyDetectionStrategies) {
583             var anomalyLengths = this._executeStrategy(strategy, currentTimeSeriesData, [movingAverageValues, envelopeDelta]);
584             for (var i = 0; i < currentTimeSeriesData.length; i++)
585                 isAnomalyArray[i] = isAnomalyArray[i] || anomalyLengths[i];
586         }
587         for (var i = 0; i < isAnomalyArray.length; i++) {
588             if (!isAnomalyArray[i])
589                 continue;
590             anomalies[currentTimeSeriesData[i].measurement.id()] = true;
591             while (isAnomalyArray[i] && i < isAnomalyArray.length)
592                 ++i;
593         }
594
595         if (movingAverageIsSetByUser) {
596             return new TimeSeries(currentTimeSeriesData.map(function (point, index) {
597                 var value = movingAverageValues[index];
598                 return {
599                     measurement: point.measurement,
600                     time: point.time,
601                     value: value,
602                     interval: envelopeDelta !== null ? [value - envelopeDelta, value + envelopeDelta] : null,
603                 }
604             }));            
605         }
606     },
607     _executeStrategy: function (strategy, currentTimeSeriesData, additionalArguments)
608     {
609         var parameters = (strategy.parameterList || []).map(function (param) {
610             var parsed = parseFloat(param.value);
611             return Math.min(param.max || Infinity, Math.max(param.min || -Infinity, isNaN(parsed) ? 0 : parsed));
612         });
613         parameters.push(currentTimeSeriesData.map(function (point) { return point.value }));
614         return strategy.execute.apply(window, parameters.concat(additionalArguments));
615     },
616     _updateStrategyConfigIfNeeded: function (strategy, configName)
617     {
618         var config = null;
619         if (strategy && strategy.execute)
620             config = [strategy.id].concat((strategy.parameterList || []).map(function (param) { return param.value; }));
621
622         if (JSON.stringify(config) != JSON.stringify(this.get(configName)))
623             this.set(configName, config);
624     },
625     _updateDetails: function ()
626     {
627         var selectedPoints = this.get('selectedPoints');
628         var currentPoint = this.get('hoveredOrSelectedItem');
629         if (!selectedPoints && !currentPoint) {
630             this.set('details', null);
631             return;
632         }
633
634         var currentMeasurement;
635         var previousPoint;
636         if (!selectedPoints)
637             previousPoint = currentPoint.series.previousPoint(currentPoint);
638         else {
639             currentPoint = selectedPoints[selectedPoints.length - 1];
640             previousPoint = selectedPoints[0];
641         }
642         var currentMeasurement = currentPoint.measurement;
643         var oldMeasurement = previousPoint ? previousPoint.measurement : null;
644
645         var formattedRevisions = currentMeasurement.formattedRevisions(oldMeasurement);
646         var revisions = App.Manifest.get('repositories')
647             .filter(function (repository) { return formattedRevisions[repository.get('id')]; })
648             .map(function (repository) {
649             var revision = Ember.Object.create(formattedRevisions[repository.get('id')]);
650             revision['url'] = revision.previousRevision
651                 ? repository.urlForRevisionRange(revision.previousRevision, revision.currentRevision)
652                 : repository.urlForRevision(revision.currentRevision);
653             revision['name'] = repository.get('name');
654             revision['repository'] = repository;
655             return revision; 
656         });
657
658         var buildNumber = null;
659         var buildURL = null;
660         if (!selectedPoints) {
661             buildNumber = currentMeasurement.buildNumber();
662             var builder = App.Manifest.builder(currentMeasurement.builderId());
663             if (builder)
664                 buildURL = builder.urlFromBuildNumber(buildNumber);
665         }
666
667         this.set('details', Ember.Object.create({
668             status: this.computeStatus(currentPoint, previousPoint),
669             buildNumber: buildNumber,
670             buildURL: buildURL,
671             buildTime: currentMeasurement.formattedBuildTime(),
672             revisions: revisions,
673         }));
674     }.observes('hoveredOrSelectedItem', 'selectedPoints'),
675 });
676
677 App.encodePrettifiedJSON = function (plain)
678 {
679     function numberIfPossible(string) {
680         return string == parseInt(string) ? parseInt(string) : string;
681     }
682
683     function recursivelyConvertNumberIfPossible(input) {
684         if (input instanceof Array) {
685             return input.map(recursivelyConvertNumberIfPossible);
686         }
687         return numberIfPossible(input);
688     }
689
690     return JSON.stringify(recursivelyConvertNumberIfPossible(plain))
691         .replace(/\[/g, '(').replace(/\]/g, ')').replace(/\,/g, '-');
692 }
693
694 App.decodePrettifiedJSON = function (encoded)
695 {
696     var parsed = encoded.replace(/\(/g, '[').replace(/\)/g, ']').replace(/\-/g, ',');
697     try {
698         return JSON.parse(parsed);
699     } catch (exception) {
700         return null;
701     }
702 }
703
704 App.ChartsController = Ember.Controller.extend({
705     queryParams: ['paneList', 'zoom', 'since'],
706     needs: ['pane'],
707     _currentEncodedPaneList: null,
708     panes: [],
709     platforms: null,
710     sharedZoom: null,
711     startTime: null,
712     present: Date.now(),
713     defaultSince: Date.now() - 7 * 24 * 3600 * 1000,
714
715     addPane: function (pane)
716     {
717         this.panes.unshiftObject(pane);
718     },
719
720     removePane: function (pane)
721     {
722         this.panes.removeObject(pane);
723     },
724
725     refreshPanes: function()
726     {
727         var paneList = this.get('paneList');
728         if (paneList === this._currentEncodedPaneList)
729             return;
730
731         var panes = this._parsePaneList(paneList || '[]');
732         if (!panes) {
733             console.log('Failed to parse', jsonPaneList, exception);
734             return;
735         }
736         this.set('panes', panes);
737         this._currentEncodedPaneList = paneList;
738     }.observes('paneList').on('init'),
739
740     refreshZoom: function()
741     {
742         var zoom = this.get('zoom');
743         if (!zoom) {
744             this.set('sharedZoom', null);
745             return;
746         }
747
748         zoom = zoom.split('-');
749         var selection = new Array(2);
750         try {
751             selection[0] = new Date(parseFloat(zoom[0]));
752             selection[1] = new Date(parseFloat(zoom[1]));
753         } catch (error) {
754             console.log('Failed to parse the zoom', zoom);
755         }
756         this.set('sharedZoom', selection);
757
758         var startTime = this.get('startTime');
759         if (startTime && startTime > selection[0])
760             this.set('startTime', selection[0]);
761
762     }.observes('zoom').on('init'),
763
764     _startTimeChanged: function () {
765         this.set('sharedDomain', [this.get('startTime'), this.get('present')]);
766         this._scheduleQueryStringUpdate();
767     }.observes('startTime'),
768
769     _sinceChanged: function () {
770         var since = parseInt(this.get('since'));
771         if (isNaN(since))
772             since = this.defaultSince;
773         this.set('startTime', new Date(since));
774     }.observes('since').on('init'),
775
776     _parsePaneList: function (encodedPaneList)
777     {
778         var parsedPaneList = App.decodePrettifiedJSON(encodedPaneList);
779         if (!parsedPaneList)
780             return null;
781
782         // FIXME: Don't re-create all panes.
783         var self = this;
784         return parsedPaneList.map(function (paneInfo) {
785             var timeRange = null;
786             var selectedItem = null;
787             if (paneInfo[2] instanceof Array) {
788                 var timeRange = paneInfo[2];
789                 try {
790                     timeRange = [new Date(timeRange[0]), new Date(timeRange[1])];
791                 } catch (error) {
792                     console.log("Failed to parse the time range:", timeRange, error);
793                 }
794             } else
795                 selectedItem = paneInfo[2];
796
797             return App.Pane.create({
798                 store: self.store,
799                 info: paneInfo,
800                 platformId: paneInfo[0],
801                 metricId: paneInfo[1],
802                 selectedItem: selectedItem,
803                 timeRange: timeRange,
804                 showFullYAxis: paneInfo[3],
805                 movingAverageConfig: paneInfo[4],
806                 envelopingConfig: paneInfo[5],
807             });
808         });
809     },
810
811     _serializePaneList: function (panes)
812     {
813         if (!panes.length)
814             return undefined;
815         var self = this;
816         return App.encodePrettifiedJSON(panes.map(function (pane) {
817             return [
818                 pane.get('platformId'),
819                 pane.get('metricId'),
820                 pane.get('timeRange') ? pane.get('timeRange').map(function (date) { return date.getTime() }) : pane.get('selectedItem'),
821                 pane.get('showFullYAxis'),
822                 pane.get('movingAverageConfig'),
823                 pane.get('envelopingConfig'),
824             ];
825         }));
826     },
827
828     _scheduleQueryStringUpdate: function ()
829     {
830         Ember.run.debounce(this, '_updateQueryString', 1000);
831     }.observes('sharedZoom', 'panes.@each.platform', 'panes.@each.metric', 'panes.@each.selectedItem', 'panes.@each.timeRange',
832         'panes.@each.showFullYAxis', 'panes.@each.movingAverageConfig', 'panes.@each.envelopingConfig'),
833
834     _updateQueryString: function ()
835     {
836         this._currentEncodedPaneList = this._serializePaneList(this.get('panes'));
837         this.set('paneList', this._currentEncodedPaneList);
838
839         var zoom = undefined;
840         var sharedZoom = this.get('sharedZoom');
841         if (sharedZoom && !App.domainsAreEqual(sharedZoom, this.get('sharedDomain')))
842             zoom = +sharedZoom[0] + '-' + +sharedZoom[1];
843         this.set('zoom', zoom);
844
845         if (this.get('startTime') - this.defaultSince)
846             this.set('since', this.get('startTime') - 0);
847     },
848
849     actions: {
850         addPaneByMetricAndPlatform: function (param)
851         {
852             this.addPane(App.Pane.create({
853                 store: this.store,
854                 platformId: param.platform.get('id'),
855                 metricId: param.metric.get('id'),
856                 showingDetails: false
857             }));
858         },
859     },
860
861     init: function ()
862     {
863         this._super();
864         var self = this;
865         App.buildPopup(this.store, 'addPaneByMetricAndPlatform').then(function (platforms) {
866             self.set('platforms', platforms);
867         });
868     },
869 });
870
871 App.buildPopup = function(store, action, position)
872 {
873     return App.Manifest.fetch(store).then(function () {
874         return App.Manifest.get('platforms').map(function (platform) {
875             return App.PlatformProxyForPopup.create({content: platform,
876                 action: action, position: position});
877         });
878     });
879 }
880
881 App.PlatformProxyForPopup = Ember.ObjectProxy.extend({
882     children: function ()
883     {
884         var platform = this.content;
885         var containsTest = this.content.containsTest.bind(this.content);
886         var action = this.get('action');
887         var position = this.get('position');
888         return App.Manifest.get('topLevelTests')
889             .filter(containsTest)
890             .map(function (test) {
891                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
892             });
893     }.property('App.Manifest.topLevelTests'),
894 });
895
896 App.TestProxyForPopup = Ember.ObjectProxy.extend({
897     platform: null,
898     children: function ()
899     {
900         var platform = this.get('platform');
901         var action = this.get('action');
902         var position = this.get('position');
903
904         var childTests = this.get('childTests')
905             .filter(function (test) { return platform.containsTest(test); })
906             .map(function (test) {
907                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
908             });
909
910         var metrics = this.get('metrics')
911             .filter(function (metric) { return platform.containsMetric(metric); })
912             .map(function (metric) {
913                 var aggregator = metric.get('aggregator');
914                 return {
915                     actionName: action,
916                     actionArgument: {platform: platform, metric: metric, position:position},
917                     label: metric.get('label')
918                 };
919             });
920
921         if (childTests.length && metrics.length)
922             metrics.push({isSeparator: true});
923
924         return metrics.concat(childTests);
925     }.property('childTests', 'metrics'),
926 });
927
928 App.domainsAreEqual = function (domain1, domain2) {
929     return (!domain1 && !domain2) || (domain1 && domain2 && !(domain1[0] - domain2[0]) && !(domain1[1] - domain2[1]));
930 }
931
932 App.PaneController = Ember.ObjectController.extend({
933     needs: ['charts'],
934     sharedTime: Ember.computed.alias('parentController.sharedTime'),
935     sharedSelection: Ember.computed.alias('parentController.sharedSelection'),
936     selection: null,
937     actions: {
938         toggleDetails: function()
939         {
940             this.toggleProperty('showingDetails');
941         },
942         close: function ()
943         {
944             this.parentController.removePane(this.get('model'));
945         },
946         toggleBugsPane: function ()
947         {
948             if (this.toggleProperty('showingAnalysisPane')) {
949                 this.set('showingSearchPane', false);
950                 this.set('showingStatPane', false);
951             }
952         },
953         toggleShowOutlier: function ()
954         {
955             var pane = this.get('model');
956             pane.toggleProperty('showOutlier');
957             var chartData = pane.get('chartData');
958             if (!chartData)
959                 return;
960             pane._setNewChartData(chartData);
961         },
962         createAnalysisTask: function ()
963         {
964             var name = this.get('newAnalysisTaskName');
965             var points = this.get('selectedPoints');
966             Ember.assert('The analysis name should not be empty', name);
967             Ember.assert('There should be at least two points in the range', points && points.length >= 2);
968
969             var newWindow = window.open();
970             var self = this;
971             App.AnalysisTask.create(name, points[0].measurement, points[points.length - 1].measurement).then(function (data) {
972                 // FIXME: Update the UI to show the new analysis task.
973                 var url = App.Router.router.generate('analysisTask', data['taskId']);
974                 newWindow.location.href = '#' + url;
975                 self.get('model').fetchAnalyticRanges();
976             }, function (error) {
977                 newWindow.close();
978                 if (error === 'DuplicateAnalysisTask') {
979                     // FIXME: Duplicate this error more gracefully.
980                 }
981                 alert(error);
982             });
983         },
984         toggleSearchPane: function ()
985         {
986             if (!App.Manifest.repositoriesWithReportedCommits)
987                 return;
988             var model = this.get('model');
989             if (!model.get('commitSearchRepository'))
990                 model.set('commitSearchRepository', App.Manifest.repositoriesWithReportedCommits[0]);
991             if (this.toggleProperty('showingSearchPane')) {
992                 this.set('showingAnalysisPane', false);
993                 this.set('showingStatPane', false);
994             }
995         },
996         searchCommit: function () {
997             var model = this.get('model');
998             model.searchCommit(model.get('commitSearchRepository'), model.get('commitSearchKeyword'));                
999         },
1000         toggleStatPane: function ()
1001         {
1002             if (this.toggleProperty('showingStatPane')) {
1003                 this.set('showingSearchPane', false);
1004                 this.set('showingAnalysisPane', false);
1005             }
1006         },
1007         zoomed: function (selection)
1008         {
1009             this.set('mainPlotDomain', selection ? selection : this.get('overviewDomain'));
1010             if (selection)
1011                 this.set('overviewSelection', selection);
1012             Ember.run.debounce(this, 'propagateZoom', 100);
1013         },
1014     },
1015     _overviewSelectionChanged: function ()
1016     {
1017         var overviewSelection = this.get('overviewSelection');
1018         if (App.domainsAreEqual(overviewSelection, this.get('mainPlotDomain')))
1019             return;
1020         this.set('mainPlotDomain', overviewSelection || this.get('overviewDomain'));
1021         Ember.run.debounce(this, 'propagateZoom', 100);
1022     }.observes('overviewSelection'),
1023     _sharedDomainChanged: function ()
1024     {
1025         var newDomain = this.get('parentController').get('sharedDomain');
1026         if (App.domainsAreEqual(newDomain, this.get('overviewDomain')))
1027             return;
1028         this.set('overviewDomain', newDomain);
1029         if (!this.get('overviewSelection'))
1030             this.set('mainPlotDomain', newDomain);
1031     }.observes('parentController.sharedDomain').on('init'),
1032     propagateZoom: function ()
1033     {
1034         this.get('parentController').set('sharedZoom', this.get('mainPlotDomain'));
1035     },
1036     _sharedZoomChanged: function ()
1037     {
1038         var newSelection = this.get('parentController').get('sharedZoom');
1039         if (App.domainsAreEqual(newSelection, this.get('mainPlotDomain')))
1040             return;
1041         this.set('mainPlotDomain', newSelection || this.get('overviewDomain'));
1042         this.set('overviewSelection', newSelection);
1043     }.observes('parentController.sharedZoom').on('init'),
1044     _updateCanAnalyze: function ()
1045     {
1046         var pane = this.get('model');
1047         var points = pane.get('selectedPoints');
1048         this.set('cannotAnalyze', !this.get('newAnalysisTaskName') || !points || points.length < 2);
1049         this.set('cannotMarkOutlier', !!points || !this.get('selectedItem'));
1050
1051         var selectedMeasurement = this.selectedMeasurement();
1052         this.set('selectedItemIsMarkedOutlier', selectedMeasurement && selectedMeasurement.markedOutlier());
1053
1054     }.observes('newAnalysisTaskName', 'model.selectedPoints', 'model.selectedItem').on('init'),
1055     selectedMeasurement: function () {
1056         var chartData = this.get('model').get('chartData');
1057         var selectedItem = this.get('selectedItem');
1058         if (!chartData || !selectedItem)
1059             return null;
1060         var point = chartData.current.findPointByMeasurementId(selectedItem);
1061         Ember.assert('selectedItem should always be in the current chart data', point);
1062         return point.measurement;
1063     },
1064     showOutlierTitle: function ()
1065     {
1066         return this.get('showOutlier') ? 'Hide outliers' : 'Show outliers';
1067     }.property('showOutlier'),
1068     _selectedItemIsMarkedOutlierDidChange: function ()
1069     {
1070         var selectedMeasurement = this.selectedMeasurement();
1071         if (!selectedMeasurement)
1072             return;
1073         var selectedItemIsMarkedOutlier = this.get('selectedItemIsMarkedOutlier');
1074         if (selectedMeasurement.markedOutlier() == selectedItemIsMarkedOutlier)
1075             return;
1076         var pane = this.get('model');
1077         selectedMeasurement.setMarkedOutlier(!!selectedItemIsMarkedOutlier).then(function () {
1078             alert(selectedItemIsMarkedOutlier ? 'Marked the point as an outlier' : 'The point is no longer marked as an outlier');
1079             pane.refetchRuns();
1080         }, function (error) {
1081             alert('Failed to update the status:' + error);
1082         });
1083     }.observes('selectedItemIsMarkedOutlier'),
1084 });
1085
1086 App.AnalysisRoute = Ember.Route.extend({
1087     model: function () {
1088         return this.store.findAll('analysisTask').then(function (tasks) {
1089             return Ember.Object.create({'tasks': tasks});
1090         });
1091     },
1092 });
1093
1094 App.AnalysisTaskRoute = Ember.Route.extend({
1095     model: function (param)
1096     {
1097         return this.store.find('analysisTask', param.taskId);
1098     },
1099 });
1100
1101 App.AnalysisTaskController = Ember.Controller.extend({
1102     label: Ember.computed.alias('model.name'),
1103     platform: Ember.computed.alias('model.platform'),
1104     metric: Ember.computed.alias('model.metric'),
1105     details: Ember.computed.alias('pane.details'),
1106     roots: [],
1107     bugTrackers: [],
1108     possibleRepetitionCounts: [1, 2, 3, 4, 5, 6],
1109     _taskUpdated: function ()
1110     {
1111         var model = this.get('model');
1112         if (!model)
1113             return;
1114
1115         App.Manifest.fetch(this.store).then(this._fetchedManifest.bind(this));
1116         this.set('pane', App.Pane.create({
1117             store: this.store,
1118             platformId: model.get('platform').get('id'),
1119             metricId: model.get('metric').get('id'),
1120         }));
1121
1122         var self = this;
1123         model.get('testGroups').then(function (groups) {
1124             self.set('testGroupPanes', groups.map(function (group) { return App.TestGroupPane.create({content: group}); }));
1125         });
1126     }.observes('model', 'model.testGroups').on('init'),
1127     _fetchedManifest: function ()
1128     {
1129         var trackerIdToBugNumber = {};
1130         this.get('model').get('bugs').forEach(function (bug) {
1131             trackerIdToBugNumber[bug.get('bugTracker').get('id')] = bug.get('number');
1132         });
1133
1134         this.set('bugTrackers', App.Manifest.get('bugTrackers').map(function (bugTracker) {
1135             var bugNumber = trackerIdToBugNumber[bugTracker.get('id')];
1136             return Ember.ObjectProxy.create({
1137                 content: bugTracker,
1138                 bugNumber: bugNumber,
1139                 editedBugNumber: bugNumber,
1140             });
1141         }));
1142     },
1143     _chartDataChanged: function ()
1144     {
1145         var pane = this.get('pane');
1146         if (!pane)
1147             return;
1148
1149         var chartData = pane.get('chartData');
1150         if (!chartData)
1151             return null;
1152
1153         var currentTimeSeries = chartData.current;
1154         if (!currentTimeSeries)
1155             return null; // FIXME: Report an error.
1156
1157         var start = currentTimeSeries.findPointByMeasurementId(this.get('model').get('startRun'));
1158         var end = currentTimeSeries.findPointByMeasurementId(this.get('model').get('endRun'));
1159         if (!start || !end)
1160             return null; // FIXME: Report an error.
1161
1162         var highlightedItems = {};
1163         highlightedItems[start.measurement.id()] = true;
1164         highlightedItems[end.measurement.id()] = true;
1165
1166         var formatedPoints = currentTimeSeries.seriesBetweenPoints(start, end).map(function (point, index) {
1167             return {
1168                 id: point.measurement.id(),
1169                 measurement: point.measurement,
1170                 label: 'Point ' + (index + 1),
1171                 value: chartData.formatWithUnit(point.value),
1172             };
1173         });
1174
1175         var margin = (end.time - start.time) * 0.1;
1176         this.set('highlightedItems', highlightedItems);
1177         this.set('overviewEndPoints', [start, end]);
1178         this.set('analysisPoints', formatedPoints);
1179
1180         var overviewDomain = [start.time - margin, +end.time + margin];
1181
1182         var testGroupPanes = this.get('testGroupPanes');
1183         if (testGroupPanes) {
1184             testGroupPanes.setEach('overviewPane', pane);
1185             testGroupPanes.setEach('overviewDomain', overviewDomain);
1186         }
1187
1188         this.set('overviewDomain', overviewDomain);
1189     }.observes('pane.chartData'),
1190     updateRootConfigurations: function ()
1191     {
1192         var analysisPoints = this.get('analysisPoints');
1193         if (!analysisPoints)
1194             return;
1195         var repositoryToRevisions = {};
1196         analysisPoints.forEach(function (point, pointIndex) {
1197             var revisions = point.measurement.formattedRevisions();
1198             for (var repositoryId in revisions) {
1199                 if (!repositoryToRevisions[repositoryId])
1200                     repositoryToRevisions[repositoryId] = new Array(analysisPoints.length);
1201                 var revision = revisions[repositoryId];
1202                 repositoryToRevisions[repositoryId][pointIndex] = {
1203                     label: point.label + ': ' + revision.label,
1204                     value: revision.currentRevision,
1205                 };
1206             }
1207         });
1208
1209         var self = this;
1210         this.get('model').get('triggerable').then(function (triggerable) {
1211             if (!triggerable)
1212                 return;
1213
1214             self.set('configurations', ['A', 'B']);
1215             self.set('rootConfigurations', triggerable.get('acceptedRepositories').map(function (repository) {
1216                 var repositoryId = repository.get('id');
1217                 var options = [{label: 'None'}].concat((repositoryToRevisions[repositoryId] || []).map(function (option, index) {
1218                     if (!option || !option['value'])
1219                         return {value: '', label: analysisPoints[index].label + ': None'}; 
1220                     return option;
1221                 }));
1222                 return Ember.Object.create({
1223                     repository: repository,
1224                     name: repository.get('name'),
1225                     sets: [
1226                         Ember.Object.create({name: 'A[' + repositoryId + ']',
1227                             options: options,
1228                             selection: options[1]}),
1229                         Ember.Object.create({name: 'B[' + repositoryId + ']',
1230                             options: options,
1231                             selection: options[options.length - 1]}),
1232                     ],
1233                 });
1234             }));
1235         });
1236     }.observes('analysisPoints'),
1237     actions: {
1238         associateBug: function (bugTracker, bugNumber)
1239         {
1240             var model = this.get('model');
1241             this.store.createRecord('bug',
1242                 {task: this.get('model'), bugTracker: bugTracker.get('content'), number: bugNumber}).save().then(function () {
1243                     // FIXME: Should we notify the user?
1244                 }, function (error) {
1245                     alert('Failed to associate the bug: ' + error);
1246                 });
1247         },
1248         createTestGroup: function (name, repetitionCount)
1249         {
1250             var analysisTask = this.get('model');
1251             if (analysisTask.get('testGroups').isAny('name', name)) {
1252                 alert('Cannot create two test groups of the same name.');
1253                 return;
1254             }
1255
1256             var roots = {};
1257             var rootConfigurations = this.get('rootConfigurations').toArray();
1258             for (var root of rootConfigurations) {
1259                 var sets = root.get('sets');
1260                 var hasSelection = function (item) { return item.get('selection') && item.get('selection').value; };
1261                 if (!sets.any(hasSelection))
1262                     continue;
1263                 if (!sets.every(hasSelection)) {
1264                     alert('Only some configuration specifies ' + root.get('name'));
1265                     return;
1266                 }
1267                 roots[root.get('name')] = sets.map(function (item) { return item.get('selection').value; });                
1268             }
1269
1270             App.TestGroup.create(analysisTask, name, roots, repetitionCount).then(function () {
1271             }, function (error) {
1272                 alert('Failed to create a new test group:' + error);
1273             });
1274         },
1275         toggleShowRequestList: function (configuration)
1276         {
1277             configuration.toggleProperty('showRequestList');
1278         }
1279     },
1280     _updateRootsBySelectedPoints: function ()
1281     {
1282         var rootConfigurations = this.get('rootConfigurations');
1283         var pane = this.get('pane');
1284         if (!rootConfigurations || !pane)
1285             return;
1286
1287         var rootSetPoints;
1288         var selectedPoints = pane.get('selectedPoints');
1289         if (selectedPoints && selectedPoints.length >= 2)
1290             rootSetPoints = [selectedPoints[0], selectedPoints[selectedPoints.length - 1]];
1291         else
1292             rootSetPoints = this.get('overviewEndPoints');
1293         if (!rootSetPoints)
1294             return;
1295
1296         rootConfigurations.forEach(function (root) {
1297             root.get('sets').forEach(function (set, setIndex) {
1298                 if (setIndex >= rootSetPoints.length)
1299                     return;
1300                 var targetRevision = rootSetPoints[setIndex].measurement.revisionForRepository(root.get('repository').get('id'));
1301                 var selectedOption;
1302                 if (targetRevision)
1303                     selectedOption = set.get('options').find(function (option) { return option.value == targetRevision; });
1304                 set.set('selection', selectedOption || set.get('options')[0]);
1305             });
1306         });
1307
1308     }.observes('pane.selectedPoints'),
1309 });
1310
1311 App.TestGroupPane = Ember.ObjectProxy.extend({
1312     _populate: function ()
1313     {
1314         var buildRequests = this.get('buildRequests');
1315         var testResults = this.get('testResults');
1316         if (!buildRequests || !testResults)
1317             return [];
1318
1319         var repositories = this._computeRepositoryList();
1320         this.set('repositories', repositories);
1321
1322         var requestsByRooSet = this._groupRequestsByConfigurations(buildRequests);
1323
1324         var configurations = [];
1325         var index = 0;
1326         var range = {min: Infinity, max: -Infinity};
1327         for (var rootSetId in requestsByRooSet) {
1328             var configLetter = String.fromCharCode('A'.charCodeAt(0) + index++);
1329             configurations.push(this._createConfigurationSummary(requestsByRooSet[rootSetId], configLetter, range));
1330         }
1331
1332         var margin = 0.1 * (range.max - range.min);
1333         range.max += margin;
1334         range.min -= margin;
1335
1336         this.set('configurations', configurations);
1337
1338         var comparisons = [];
1339         for (var i = 0; i < configurations.length - 1; i++) {
1340             var summary1 = configurations[i].summary;
1341             for (var j = i + 1; j < configurations.length; j++) {
1342                 var summary2 = configurations[j].summary;
1343                 comparisons.push({
1344                     label: summary1.configLetter + ' / ' + summary2.configLetter,
1345                     result: this._computeStatisticalSignificance(summary1.measuredValues, summary2.measuredValues)
1346                 });
1347             }
1348         }
1349         this.set('comparisons', comparisons);
1350     }.observes('testResults', 'buildRequests'),
1351     _computeStatisticalSignificance: function (values1, values2)
1352     {
1353         var tFormatter = d3.format('.3g');
1354         var probabilityFormatter = d3.format('.2p');
1355         var statistics = Statistics.probabilityRangeForWelchsT(values1, values2);
1356         if (isNaN(statistics.t) || isNaN(statistics.degreesOfFreedom))
1357             return 'N/A';
1358
1359         var details = ' (t=' + tFormatter(statistics.t) + ' df=' + tFormatter(statistics.degreesOfFreedom) + ')';
1360
1361         if (!statistics.range[0])
1362             return 'Not statistically significant' + details;
1363
1364         var lowerLimit = probabilityFormatter(statistics.range[0]);
1365         if (!statistics.range[1])
1366             return 'Statistical significance > ' + lowerLimit + details;
1367
1368         return lowerLimit + ' < Statistical significance < ' + probabilityFormatter(statistics.range[1]) + details;
1369     },
1370     _updateReferenceChart: function ()
1371     {
1372         var configurations = this.get('configurations');
1373         var chartData = this.get('overviewPane') ? this.get('overviewPane').get('chartData') : null;
1374         if (!configurations || !chartData || this.get('referenceChart'))
1375             return;
1376
1377         var currentTimeSeries = chartData.current;
1378         if (!currentTimeSeries)
1379             return;
1380
1381         var repositories = this.get('repositories');
1382         var highlightedItems = {};
1383         var failedToFindPoint = false;
1384         configurations.forEach(function (config) {
1385             var revisions = {};
1386             config.get('rootSet').get('roots').forEach(function (root) {
1387                 revisions[root.get('repository').get('id')] = root.get('revision');
1388             });
1389             var point = currentTimeSeries.findPointByRevisions(revisions);
1390             if (!point) {
1391                 failedToFindPoint = true;
1392                 return;
1393             }
1394             highlightedItems[point.measurement.id()] = true;
1395         });
1396         if (failedToFindPoint)
1397             return;
1398
1399         this.set('referenceChart', {
1400             data: chartData,
1401             highlightedItems: highlightedItems,
1402         });
1403     }.observes('configurations', 'overviewPane.chartData'),
1404     _computeRepositoryList: function ()
1405     {
1406         var specifiedRepositories = new Ember.Set();
1407         (this.get('rootSets') || []).forEach(function (rootSet) {
1408             (rootSet.get('roots') || []).forEach(function (root) {
1409                 specifiedRepositories.add(root.get('repository'));
1410             });
1411         });
1412         var reportedRepositories = new Ember.Set();
1413         var testResults = this.get('testResults');
1414         (this.get('buildRequests') || []).forEach(function (request) {
1415             var point = testResults.current.findPointByBuild(request.get('build'));
1416             if (!point)
1417                 return;
1418
1419             var revisionByRepositoryId = point.measurement.formattedRevisions();
1420             for (var repositoryId in revisionByRepositoryId) {
1421                 var repository = App.Manifest.repository(repositoryId);
1422                 if (!specifiedRepositories.contains(repository))
1423                     reportedRepositories.add(repository);
1424             }
1425         });
1426         return specifiedRepositories.sortBy('name').concat(reportedRepositories.sortBy('name'));
1427     },
1428     _groupRequestsByConfigurations: function (requests, repositoryList)
1429     {
1430         var rootSetIdToRequests = {};
1431         var testGroup = this;
1432         requests.forEach(function (request) {
1433             var rootSetId = request.get('rootSet').get('id');
1434             if (!rootSetIdToRequests[rootSetId])
1435                 rootSetIdToRequests[rootSetId] = [];
1436             rootSetIdToRequests[rootSetId].push(request);
1437         });
1438         return rootSetIdToRequests;
1439     },
1440     _createConfigurationSummary: function (buildRequests, configLetter, range)
1441     {
1442         var repositories = this.get('repositories');
1443         var testResults = this.get('testResults');
1444         var requests = buildRequests.map(function (originalRequest) {
1445             var point = testResults.current.findPointByBuild(originalRequest.get('build'));
1446             var revisionByRepositoryId = point ? point.measurement.formattedRevisions() : {};
1447             return Ember.ObjectProxy.create({
1448                 content: originalRequest,
1449                 revisionList: repositories.map(function (repository, index) {
1450                     return (revisionByRepositoryId[repository.get('id')] || {label:null}).label;
1451                 }),
1452                 value: point ? point.value : null,
1453                 valueRange: range,
1454                 formattedValue: point ? testResults.formatWithUnit(point.value) : null,
1455                 buildLabel: point ? 'Build ' + point.measurement.buildNumber() : null,
1456             });
1457         });
1458
1459         var rootSet = requests ? requests[0].get('rootSet') : null;
1460         var summaryRevisions = repositories.map(function (repository, index) {
1461             var revision = rootSet ? rootSet.revisionForRepository(repository) : null;
1462             if (!revision)
1463                 return requests[0].get('revisionList')[index];
1464             return Measurement.formatRevisionRange(revision).label;
1465         });
1466
1467         requests.forEach(function (request) {
1468             var revisionList = request.get('revisionList');
1469             repositories.forEach(function (repository, index) {
1470                 if (revisionList[index] == summaryRevisions[index])
1471                     revisionList[index] = null;
1472             });
1473         });
1474
1475         var valuesInConfig = requests.mapBy('value').filter(function (value) { return typeof(value) === 'number' && !isNaN(value); });
1476         var sum = Statistics.sum(valuesInConfig);
1477         var ciDelta = Statistics.confidenceIntervalDelta(0.95, valuesInConfig.length, sum, Statistics.squareSum(valuesInConfig));
1478         var mean = sum / valuesInConfig.length;
1479
1480         range.min = Math.min(range.min, Statistics.min(valuesInConfig));
1481         range.max = Math.max(range.max, Statistics.max(valuesInConfig));
1482         if (ciDelta && !isNaN(ciDelta)) {
1483             range.min = Math.min(range.min, mean - ciDelta);
1484             range.max = Math.max(range.max, mean + ciDelta);
1485         }
1486
1487         var summary = Ember.Object.create({
1488             isAverage: true,
1489             configLetter: configLetter,
1490             revisionList: summaryRevisions,
1491             formattedValue: isNaN(mean) ? null : testResults.formatWithDeltaAndUnit(mean, ciDelta),
1492             value: mean,
1493             measuredValues: valuesInConfig,
1494             confidenceIntervalDelta: ciDelta,
1495             valueRange: range,
1496             statusLabel: App.BuildRequest.aggregateStatuses(requests),
1497         });
1498
1499         return Ember.Object.create({summary: summary, requests: requests, rootSet: rootSet});
1500     },
1501 });
1502
1503 App.BoxPlotComponent = Ember.Component.extend({
1504     classNames: ['box-plot'],
1505     range: null,
1506     value: null,
1507     delta: null,
1508     didInsertElement: function ()
1509     {
1510         var element = this.get('element');
1511         var svg = d3.select(element).append('svg')
1512             .attr('viewBox', '0 0 100 20')
1513             .attr('preserveAspectRatio', 'none')
1514             .style({width: '100%', height: '100%'});
1515
1516         this._percentageRect = svg
1517             .append('rect')
1518             .attr('x', 0)
1519             .attr('y', 0)
1520             .attr('width', 0)
1521             .attr('height', 20)
1522             .attr('class', 'percentage');
1523
1524         this._deltaRect = svg
1525             .append('rect')
1526             .attr('x', 0)
1527             .attr('y', 5)
1528             .attr('width', 0)
1529             .attr('height', 10)
1530             .attr('class', 'delta')
1531             .attr('opacity', 0.5)
1532         this._updateBars();
1533     },
1534     _updateBars: function ()
1535     {
1536         if (!this._percentageRect || typeof(this._percentage) !== 'number' || isNaN(this._percentage))
1537             return;
1538
1539         this._percentageRect.attr('width', this._percentage);
1540         if (typeof(this._delta) === 'number' && !isNaN(this._delta)) {
1541             this._deltaRect.attr('x', this._percentage - this._delta);
1542             this._deltaRect.attr('width', this._delta * 2);
1543         }
1544     },
1545     valueChanged: function ()
1546     {
1547         var range = this.get('range');
1548         var value = this.get('value');
1549         if (!range || !value)
1550             return;
1551         var scalingFactor = 100 / (range.max - range.min);
1552         var percentage = (value - range.min) * scalingFactor;
1553         this._percentage = percentage;
1554         this._delta = this.get('delta') * scalingFactor;
1555         this._updateBars();
1556     }.observes('value', 'range').on('init'),
1557 });