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