From: Dan Vanderkam Date: Thu, 29 Aug 2013 03:10:07 +0000 (-0400) Subject: misc merge cleanup X-Git-Url: https://adrianiainlam.tk/git/?a=commitdiff_plain;h=e47c62c7c85793b603dd9389aeeae7451d6e7a99;p=dygraphs.git misc merge cleanup --- diff --git a/datahandler/bars.js b/datahandler/bars.js index 914ee27..c1fe47d 100644 --- a/datahandler/bars.js +++ b/datahandler/bars.js @@ -36,8 +36,8 @@ BarsHandler.prototype.onPointsCreated_ = function(series, points) { var point = points[i]; point.y_top = NaN; point.y_bottom = NaN; - point.yval_minus = DygraphLayout.parseFloat_(item[2][0]); - point.yval_plus = DygraphLayout.parseFloat_(item[2][1]); + point.yval_minus = Dygraph.parseFloat(item[2][0]); + point.yval_plus = Dygraph.parseFloat(item[2][1]); } }; @@ -69,8 +69,8 @@ BarsHandler.prototype.onLineEvaluated = function(points, axis, logscale) { for (var j = 0; j < points.length; j++) { // Copy over the error terms point = points[j]; - point.y_top = DygraphLayout._calcYNormal(axis, point.yval_minus, logscale); - point.y_bottom = DygraphLayout._calcYNormal(axis, point.yval_plus, logscale); + point.y_top = DygraphLayout.calcYNormal_(axis, point.yval_minus, logscale); + point.y_bottom = DygraphLayout.calcYNormal_(axis, point.yval_plus, logscale); } }; diff --git a/datahandler/datahandler.js b/datahandler/datahandler.js index 5ed0112..39faf9e 100644 --- a/datahandler/datahandler.js +++ b/datahandler/datahandler.js @@ -128,11 +128,11 @@ Dygraph.DataHandler = function () { for ( var i = 0; i < series.length; ++i) { var item = series[i]; var yraw = item[1]; - var yval = yraw === null ? null : DygraphLayout.parseFloat_(yraw); + var yval = yraw === null ? null : Dygraph.parseFloat(yraw); var point = { x : NaN, y : NaN, - xval : DygraphLayout.parseFloat_(item[0]), + xval : Dygraph.parseFloat(item[0]), yval : yval, name : setName, // TODO(danvk): is this really necessary? idx : i + boundaryIdStart diff --git a/dygraph-layout.js b/dygraph-layout.js index 6ee4276..e428af2 100644 --- a/dygraph-layout.js +++ b/dygraph-layout.js @@ -264,7 +264,13 @@ DygraphLayout.prototype._evaluateLimits = function() { } }; -var calcYNormal_ = function(axis, value, logscale) { +/** + * @param {DygraphAxisType} axis + * @param {number} value + * @param {boolean} logscale + * @return {number} + */ +DygraphLayout.calcYNormal_ = function(axis, value, logscale) { if (logscale) { return 1.0 - ((Dygraph.log10(value) - Dygraph.log10(axis.minyval)) * axis.ylogscale); } else { @@ -291,7 +297,7 @@ DygraphLayout.prototype._evaluateLineCharts = function() { // Range from 0-1 where 0 represents top and 1 represents bottom var yval = point.yval; if (isStacked) { - point.y_stacked = calcYNormal_( + point.y_stacked = DygraphLayout.calcYNormal_( axis, point.yval_stacked, logscale); if (yval !== null && !isNaN(yval)) { yval = point.yval_stacked; @@ -303,7 +309,7 @@ DygraphLayout.prototype._evaluateLineCharts = function() { point.yval = NaN; } } - point.y = calcYNormal_(axis, yval, logscale); + point.y = DygraphLayout.calcYNormal_(axis, yval, logscale); } this.dygraph_.dataHandler_.onLineEvaluated(points, axis, logscale); diff --git a/dygraph.js b/dygraph.js index 3fdb924..4d4f6c3 100644 --- a/dygraph.js +++ b/dygraph.js @@ -65,7 +65,7 @@ * determines whether the input data contains error ranges. For a complete * list of options, see http://dygraphs.com/options.html. */ -var Dygraph = function(div, file, opt_attrs) { +function Dygraph(div, file, opt_attrs) { // Support two-argument constructor var attrs = opt_attrs || {}; @@ -2261,6 +2261,574 @@ Dygraph.prototype.predraw_ = function() { Dygraph.PointType = undefined; /** + * Calculates point stacking for stackedGraph=true. + * + * For stacking purposes, interpolate or extend neighboring data across + * NaN values based on stackedGraphNaNFill settings. This is for display + * only, the underlying data value as shown in the legend remains NaN. + * + * @param {Array.} points Point array for a single series. + * Updates each Point's yval_stacked property. + * @param {Array.} cumulativeYval Accumulated top-of-graph stacked Y + * values for the series seen so far. Index is the row number. Updated + * based on the current series's values. + * @param {Array.} seriesExtremes Min and max values, updated + * to reflect the stacked values. + * @param {string} fillMethod Interpolation method, one of 'all', 'inside', or + * 'none'. + * @private + */ +Dygraph.stackPoints_ = function( + points, cumulativeYval, seriesExtremes, fillMethod) { + var lastXval = null; + var prevPoint = null; + var nextPoint = null; + var nextPointIdx = -1; + + // Find the next stackable point starting from the given index. + var updateNextPoint = function(idx) { + // If we've previously found a non-NaN point and haven't gone past it yet, + // just use that. + if (nextPointIdx >= idx) return; + + // We haven't found a non-NaN point yet or have moved past it, + // look towards the right to find a non-NaN point. + for (var j = idx; j < points.length; ++j) { + // Clear out a previously-found point (if any) since it's no longer + // valid, we shouldn't use it for interpolation anymore. + nextPoint = null; + if (!isNaN(points[j].yval) && points[j].yval !== null) { + nextPointIdx = j; + nextPoint = points[j]; + break; + } + } + }; + + for (var i = 0; i < points.length; ++i) { + var point = points[i]; + var xval = point.xval; + if (cumulativeYval[xval] === undefined) { + cumulativeYval[xval] = 0; + } + + var actualYval = point.yval; + if (isNaN(actualYval) || actualYval === null) { + // Interpolate/extend for stacking purposes if possible. + updateNextPoint(i); + if (prevPoint && nextPoint && fillMethod != 'none') { + // Use linear interpolation between prevPoint and nextPoint. + actualYval = prevPoint.yval + (nextPoint.yval - prevPoint.yval) * + ((xval - prevPoint.xval) / (nextPoint.xval - prevPoint.xval)); + } else if (prevPoint && fillMethod == 'all') { + actualYval = prevPoint.yval; + } else if (nextPoint && fillMethod == 'all') { + actualYval = nextPoint.yval; + } else { + actualYval = 0; + } + } else { + prevPoint = point; + } + + var stackedYval = cumulativeYval[xval]; + if (lastXval != xval) { + // If an x-value is repeated, we ignore the duplicates. + stackedYval += actualYval; + cumulativeYval[xval] = stackedYval; + } + lastXval = xval; + + point.yval_stacked = stackedYval; + + if (stackedYval > seriesExtremes[1]) { + seriesExtremes[1] = stackedYval; + } + if (stackedYval < seriesExtremes[0]) { + seriesExtremes[0] = stackedYval; + } + } +}; + + +/** + * Loop over all fields and create datasets, calculating extreme y-values for + * each series and extreme x-indices as we go. + * + * dateWindow is passed in as an explicit parameter so that we can compute + * extreme values "speculatively", i.e. without actually setting state on the + * dygraph. + * + * @param {Array.)>>} rolledSeries, where + * rolledSeries[seriesIndex][row] = raw point, where + * seriesIndex is the column number starting with 1, and + * rawPoint is [x,y] or [x, [y, err]] or [x, [y, yminus, yplus]]. + * @param {?Array.} dateWindow [xmin, xmax] pair, or null. + * @return {{ + * points: Array.>, + * seriesExtremes: Array.>, + * boundaryIds: Array.}} + * @private + */ +Dygraph.prototype.gatherDatasets_ = function(rolledSeries, dateWindow) { + var boundaryIds = []; + var points = []; + var cumulativeYval = []; // For stacked series. + var extremes = {}; // series name -> [low, high] + var seriesIdx, sampleIdx; + var firstIdx, lastIdx; + + // Loop over the fields (series). Go from the last to the first, + // because if they're stacked that's how we accumulate the values. + var num_series = rolledSeries.length - 1; + var series; + for (seriesIdx = num_series; seriesIdx >= 1; seriesIdx--) { + if (!this.visibility()[seriesIdx - 1]) continue; + + // Prune down to the desired range, if necessary (for zooming) + // Because there can be lines going to points outside of the visible area, + // we actually prune to visible points, plus one on either side. + if (dateWindow) { + series = rolledSeries[seriesIdx]; + var low = dateWindow[0]; + var high = dateWindow[1]; + + // TODO(danvk): do binary search instead of linear search. + // TODO(danvk): pass firstIdx and lastIdx directly to the renderer. + firstIdx = null; + lastIdx = null; + for (sampleIdx = 0; sampleIdx < series.length; sampleIdx++) { + if (series[sampleIdx][0] >= low && firstIdx === null) { + firstIdx = sampleIdx; + } + if (series[sampleIdx][0] <= high) { + lastIdx = sampleIdx; + } + } + + if (firstIdx === null) firstIdx = 0; + var correctedFirstIdx = firstIdx; + var isInvalidValue = true; + while (isInvalidValue && correctedFirstIdx > 0) { + correctedFirstIdx--; + // check if the y value is null. + isInvalidValue = series[correctedFirstIdx][1] === null; + } + + if (lastIdx === null) lastIdx = series.length - 1; + var correctedLastIdx = lastIdx; + isInvalidValue = true; + while (isInvalidValue && correctedLastIdx < series.length - 1) { + correctedLastIdx++; + isInvalidValue = series[correctedLastIdx][1] === null; + } + + if (correctedFirstIdx!==firstIdx) { + firstIdx = correctedFirstIdx; + } + if (correctedLastIdx !== lastIdx) { + lastIdx = correctedLastIdx; + } + + boundaryIds[seriesIdx-1] = [firstIdx, lastIdx]; + + // .slice's end is exclusive, we want to include lastIdx. + series = series.slice(firstIdx, lastIdx + 1); + } else { + series = rolledSeries[seriesIdx]; + boundaryIds[seriesIdx-1] = [0, series.length-1]; + } + + var seriesName = this.attr_("labels")[seriesIdx]; + var seriesExtremes = this.dataHandler_.getExtremeYValues(series, + dateWindow, this.attr_("stepPlot",seriesName)); + + var seriesPoints = this.dataHandler_.seriesToPoints(series, + seriesName, boundaryIds[seriesIdx-1][0]); + + if (this.attr_("stackedGraph")) { + Dygraph.stackPoints_(seriesPoints, cumulativeYval, seriesExtremes, + this.attr_("stackedGraphNaNFill")); + } + + extremes[seriesName] = seriesExtremes; + points[seriesIdx] = seriesPoints; + } + + return { points: points, extremes: extremes, boundaryIds: boundaryIds }; +}; + +/** + * Update the graph with new data. This method is called when the viewing area + * has changed. If the underlying data or options have changed, predraw_ will + * be called before drawGraph_ is called. + * + * @private + */ +Dygraph.prototype.drawGraph_ = function() { + var start = new Date(); + + // This is used to set the second parameter to drawCallback, below. + var is_initial_draw = this.is_initial_draw_; + this.is_initial_draw_ = false; + + this.layout_.removeAllDatasets(); + this.setColors_(); + this.attrs_.pointSize = 0.5 * this.attr_('highlightCircleSize'); + + var packed = this.gatherDatasets_(this.rolledSeries_, this.dateWindow_); + var points = packed.points; + var extremes = packed.extremes; + this.boundaryIds_ = packed.boundaryIds; + + this.setIndexByName_ = {}; + var labels = this.attr_("labels"); + if (labels.length > 0) { + this.setIndexByName_[labels[0]] = 0; + } + var dataIdx = 0; + for (var i = 1; i < points.length; i++) { + this.setIndexByName_[labels[i]] = i; + if (!this.visibility()[i - 1]) continue; + this.layout_.addDataset(labels[i], points[i]); + this.datasetIndex_[i] = dataIdx++; + } + + this.computeYAxisRanges_(extremes); + this.layout_.setYAxes(this.axes_); + + this.addXTicks_(); + + // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously + var tmp_zoomed_x = this.zoomed_x_; + // Tell PlotKit to use this new data and render itself + this.zoomed_x_ = tmp_zoomed_x; + this.layout_.evaluate(); + this.renderGraph_(is_initial_draw); + + if (this.attr_("timingName")) { + var end = new Date(); + Dygraph.info(this.attr_("timingName") + " - drawGraph: " + (end - start) + "ms"); + } +}; + +/** + * This does the work of drawing the chart. It assumes that the layout and axis + * scales have already been set (e.g. by predraw_). + * + * @private + */ +Dygraph.prototype.renderGraph_ = function(is_initial_draw) { + this.cascadeEvents_('clearChart'); + this.plotter_.clear(); + + if (this.attr_('underlayCallback')) { + // NOTE: we pass the dygraph object to this callback twice to avoid breaking + // users who expect a deprecated form of this callback. + this.attr_('underlayCallback')( + this.hidden_ctx_, this.layout_.getPlotArea(), this, this); + } + + var e = { + canvas: this.hidden_, + drawingContext: this.hidden_ctx_ + }; + this.cascadeEvents_('willDrawChart', e); + this.plotter_.render(); + this.cascadeEvents_('didDrawChart', e); + this.lastRow_ = -1; // because plugins/legend.js clears the legend + + // TODO(danvk): is this a performance bottleneck when panning? + // The interaction canvas should already be empty in that situation. + this.canvas_.getContext('2d').clearRect(0, 0, this.canvas_.width, + this.canvas_.height); + + if (this.attr_("drawCallback") !== null) { + this.attr_("drawCallback")(this, is_initial_draw); + } + if (is_initial_draw) { + this.readyFired_ = true; + while (this.readyFns_.length > 0) { + var fn = this.readyFns_.pop(); + fn(this); + } + } +}; + +/** + * @private + * Determine properties of the y-axes which are independent of the data + * currently being displayed. This includes things like the number of axes and + * the style of the axes. It does not include the range of each axis and its + * tick marks. + * This fills in this.axes_. + * axes_ = [ { options } ] + * indices are into the axes_ array. + */ +Dygraph.prototype.computeYAxes_ = function() { + // Preserve valueWindow settings if they exist, and if the user hasn't + // specified a new valueRange. + var valueWindows, axis, index, opts, v; + if (this.axes_ !== undefined && this.user_attrs_.hasOwnProperty("valueRange") === false) { + valueWindows = []; + for (index = 0; index < this.axes_.length; index++) { + valueWindows.push(this.axes_[index].valueWindow); + } + } + + // this.axes_ doesn't match this.attributes_.axes_.options. It's used for + // data computation as well as options storage. + // Go through once and add all the axes. + this.axes_ = []; + + for (axis = 0; axis < this.attributes_.numAxes(); axis++) { + // Add a new axis, making a copy of its per-axis options. + opts = { g : this }; + Dygraph.update(opts, this.attributes_.axisOptions(axis)); + this.axes_[axis] = opts; + } + + + // Copy global valueRange option over to the first axis. + // NOTE(konigsberg): Are these two statements necessary? + // I tried removing it. The automated tests pass, and manually + // messing with tests/zoom.html showed no trouble. + v = this.attr_('valueRange'); + if (v) this.axes_[0].valueRange = v; + + if (valueWindows !== undefined) { + // Restore valueWindow settings. + + // When going from two axes back to one, we only restore + // one axis. + var idxCount = Math.min(valueWindows.length, this.axes_.length); + + for (index = 0; index < idxCount; index++) { + this.axes_[index].valueWindow = valueWindows[index]; + } + } + + for (axis = 0; axis < this.axes_.length; axis++) { + if (axis === 0) { + opts = this.optionsViewForAxis_('y' + (axis ? '2' : '')); + v = opts("valueRange"); + if (v) this.axes_[axis].valueRange = v; + } else { // To keep old behavior + var axes = this.user_attrs_.axes; + if (axes && axes.y2) { + v = axes.y2.valueRange; + if (v) this.axes_[axis].valueRange = v; + } + } + } +}; + +/** + * Returns the number of y-axes on the chart. + * @return {Number} the number of axes. + */ +Dygraph.prototype.numAxes = function() { + return this.attributes_.numAxes(); +}; + +/** + * @private + * Returns axis properties for the given series. + * @param { String } setName The name of the series for which to get axis + * properties, e.g. 'Y1'. + * @return { Object } The axis properties. + */ +Dygraph.prototype.axisPropertiesForSeries = function(series) { + // TODO(danvk): handle errors. + return this.axes_[this.attributes_.axisForSeries(series)]; +}; + +/** + * @private + * Determine the value range and tick marks for each axis. + * @param {Object} extremes A mapping from seriesName -> [low, high] + * This fills in the valueRange and ticks fields in each entry of this.axes_. + */ +Dygraph.prototype.computeYAxisRanges_ = function(extremes) { + var isNullUndefinedOrNaN = function(num) { + return isNaN(parseFloat(num)); + }; + var numAxes = this.attributes_.numAxes(); + var ypadCompat, span, series, ypad; + + var p_axis; + + // Compute extreme values, a span and tick marks for each axis. + for (var i = 0; i < numAxes; i++) { + var axis = this.axes_[i]; + var logscale = this.attributes_.getForAxis("logscale", i); + var includeZero = this.attributes_.getForAxis("includeZero", i); + var independentTicks = this.attributes_.getForAxis("independentTicks", i); + series = this.attributes_.seriesForAxis(i); + + // Add some padding. This supports two Y padding operation modes: + // + // - backwards compatible (yRangePad not set): + // 10% padding for automatic Y ranges, but not for user-supplied + // ranges, and move a close-to-zero edge to zero except if + // avoidMinZero is set, since drawing at the edge results in + // invisible lines. Unfortunately lines drawn at the edge of a + // user-supplied range will still be invisible. If logscale is + // set, add a variable amount of padding at the top but + // none at the bottom. + // + // - new-style (yRangePad set by the user): + // always add the specified Y padding. + // + ypadCompat = true; + ypad = 0.1; // add 10% + if (this.attr_('yRangePad') !== null) { + ypadCompat = false; + // Convert pixel padding to ratio + ypad = this.attr_('yRangePad') / this.plotter_.area.h; + } + + if (series.length === 0) { + // If no series are defined or visible then use a reasonable default + axis.extremeRange = [0, 1]; + } else { + // Calculate the extremes of extremes. + var minY = Infinity; // extremes[series[0]][0]; + var maxY = -Infinity; // extremes[series[0]][1]; + var extremeMinY, extremeMaxY; + + for (var j = 0; j < series.length; j++) { + // this skips invisible series + if (!extremes.hasOwnProperty(series[j])) continue; + + // Only use valid extremes to stop null data series' from corrupting the scale. + extremeMinY = extremes[series[j]][0]; + if (extremeMinY !== null) { + minY = Math.min(extremeMinY, minY); + } + extremeMaxY = extremes[series[j]][1]; + if (extremeMaxY !== null) { + maxY = Math.max(extremeMaxY, maxY); + } + } + + // Include zero if requested by the user. + if (includeZero && !logscale) { + if (minY > 0) minY = 0; + if (maxY < 0) maxY = 0; + } + + // Ensure we have a valid scale, otherwise default to [0, 1] for safety. + if (minY == Infinity) minY = 0; + if (maxY == -Infinity) maxY = 1; + + span = maxY - minY; + // special case: if we have no sense of scale, center on the sole value. + if (span === 0) { + if (maxY !== 0) { + span = Math.abs(maxY); + } else { + // ... and if the sole value is zero, use range 0-1. + maxY = 1; + span = 1; + } + } + + var maxAxisY, minAxisY; + if (logscale) { + if (ypadCompat) { + maxAxisY = maxY + ypad * span; + minAxisY = minY; + } else { + var logpad = Math.exp(Math.log(span) * ypad); + maxAxisY = maxY * logpad; + minAxisY = minY / logpad; + } + } else { + maxAxisY = maxY + ypad * span; + minAxisY = minY - ypad * span; + + // Backwards-compatible behavior: Move the span to start or end at zero if it's + // close to zero, but not if avoidMinZero is set. + if (ypadCompat && !this.attr_("avoidMinZero")) { + if (minAxisY < 0 && minY >= 0) minAxisY = 0; + if (maxAxisY > 0 && maxY <= 0) maxAxisY = 0; + } + } + axis.extremeRange = [minAxisY, maxAxisY]; + } + if (axis.valueWindow) { + // This is only set if the user has zoomed on the y-axis. It is never set + // by a user. It takes precedence over axis.valueRange because, if you set + // valueRange, you'd still expect to be able to pan. + axis.computedValueRange = [axis.valueWindow[0], axis.valueWindow[1]]; + } else if (axis.valueRange) { + // This is a user-set value range for this axis. + var y0 = isNullUndefinedOrNaN(axis.valueRange[0]) ? axis.extremeRange[0] : axis.valueRange[0]; + var y1 = isNullUndefinedOrNaN(axis.valueRange[1]) ? axis.extremeRange[1] : axis.valueRange[1]; + if (!ypadCompat) { + if (axis.logscale) { + var logpad = Math.exp(Math.log(span) * ypad); + y0 *= logpad; + y1 /= logpad; + } else { + span = y1 - y0; + y0 -= span * ypad; + y1 += span * ypad; + } + } + axis.computedValueRange = [y0, y1]; + } else { + axis.computedValueRange = axis.extremeRange; + } + + + if (independentTicks) { + axis.independentTicks = independentTicks; + var opts = this.optionsViewForAxis_('y' + (i ? '2' : '')); + var ticker = opts('ticker'); + axis.ticks = ticker(axis.computedValueRange[0], + axis.computedValueRange[1], + this.height_, // TODO(danvk): should be area.height + opts, + this); + // Define the first independent axis as primary axis. + if (!p_axis) p_axis = axis; + } + } + if (p_axis === undefined) { + throw ("Configuration Error: At least one axis has to have the \"independentTicks\" option activated."); + } + // Add ticks. By default, all axes inherit the tick positions of the + // primary axis. However, if an axis is specifically marked as having + // independent ticks, then that is permissible as well. + for (var i = 0; i < numAxes; i++) { + var axis = this.axes_[i]; + + if (!axis.independentTicks) { + var opts = this.optionsViewForAxis_('y' + (i ? '2' : '')); + var ticker = opts('ticker'); + var p_ticks = p_axis.ticks; + var p_scale = p_axis.computedValueRange[1] - p_axis.computedValueRange[0]; + var scale = axis.computedValueRange[1] - axis.computedValueRange[0]; + var tick_values = []; + for (var k = 0; k < p_ticks.length; k++) { + var y_frac = (p_ticks[k].v - p_axis.computedValueRange[0]) / p_scale; + var y_val = axis.computedValueRange[0] + y_frac * scale; + tick_values.push(y_val); + } + + axis.ticks = ticker(axis.computedValueRange[0], + axis.computedValueRange[1], + this.height_, // TODO(danvk): should be area.height + opts, + this, + tick_values); + } + } +}; + +/** * Detects the type of the str (date or numeric) and sets the various * formatting attributes in this.attrs_ based on this type. * @param {string} str An x value.