DataGrouping.js 33.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
/**
 * (c) 2010-2018 Torstein Honsi
 *
 * License: www.highcharts.com/license
 */

'use strict';
import H from './Globals.js';
import './Utilities.js';
import './Axis.js';
import './Series.js';
import './Tooltip.js';
var addEvent = H.addEvent,
    arrayMax = H.arrayMax,
    arrayMin = H.arrayMin,
    Axis = H.Axis,
    defaultPlotOptions = H.defaultPlotOptions,
    defined = H.defined,
    each = H.each,
    extend = H.extend,
    format = H.format,
    isNumber = H.isNumber,
    merge = H.merge,
    pick = H.pick,
    Point = H.Point,
    Series = H.Series,
    Tooltip = H.Tooltip,
    wrap = H.wrap;

/* ****************************************************************************
 * Start data grouping module                                                 *
 ******************************************************************************/

/**
 * Data grouping is the concept of sampling the data values into larger
 * blocks in order to ease readability and increase performance of the
 * JavaScript charts. Highstock by default applies data grouping when
 * the points become closer than a certain pixel value, determined by
 * the `groupPixelWidth` option.
 *
 * If data grouping is applied, the grouping information of grouped
 * points can be read from the [Point.dataGroup](
 * /class-reference/Highcharts.Point#.dataGroup). If point options other than
 * the data itself are set, for example `name` or `color` or custom properties,
 * the grouping logic doesn't know how to group it. In this case the options of
 * the first point instance are copied over to the group point. This can be
 * altered through a custom `approximation` callback function.
 *
 * @product highstock
 * @apioption plotOptions.series.dataGrouping
 */

/**
 * The method of approximation inside a group. When for example 30 days
 * are grouped into one month, this determines what value should represent
 * the group. Possible values are "average", "averages", "open", "high",
 * "low", "close" and "sum". For OHLC and candlestick series the approximation
 * is "ohlc" by default, which finds the open, high, low and close values
 * within all the grouped data. For ranges, the approximation is "range",
 * which finds the low and high values. For multi-dimensional data,
 * like ranges and OHLC, "averages" will compute the average for each
 * dimension.
 *
 * Custom aggregate methods can be added by assigning a callback function
 * as the approximation. This function takes a numeric array as the
 * argument and should return a single numeric value or `null`. Note
 * that the numeric array will never contain null values, only true
 * numbers. Instead, if null values are present in the raw data, the
 * numeric array will have an `.hasNulls` property set to `true`. For
 * single-value data sets the data is available in the first argument
 * of the callback function. For OHLC data sets, all the open values
 * are in the first argument, all high values in the second etc.
 *
 * Since v4.2.7, grouping meta data is available in the approximation
 * callback from `this.dataGroupInfo`. It can be used to extract information
 * from the raw data.
 *
 * Defaults to `average` for line-type series, `sum` for columns, `range`
 * for range series and `ohlc` for OHLC and candlestick.
 *
 * @validvalue ["average", "averages", "open", "high", "low", "close", "sum"]
 * @type {String|Function}
 * @sample {highstock} stock/plotoptions/series-datagrouping-approximation
 *         Approximation callback with custom data
 * @product highstock
 * @apioption plotOptions.series.dataGrouping.approximation
 */

/**
 * Datetime formats for the header of the tooltip in a stock chart.
 * The format can vary within a chart depending on the currently selected
 * time range and the current data grouping.
 *
 * The default formats are:
 *
 * <pre>{
 *     millisecond: [
 *         '%A, %b %e, %H:%M:%S.%L', '%A, %b %e, %H:%M:%S.%L', '-%H:%M:%S.%L'
 *     ],
 *     second: ['%A, %b %e, %H:%M:%S', '%A, %b %e, %H:%M:%S', '-%H:%M:%S'],
 *     minute: ['%A, %b %e, %H:%M', '%A, %b %e, %H:%M', '-%H:%M'],
 *     hour: ['%A, %b %e, %H:%M', '%A, %b %e, %H:%M', '-%H:%M'],
 *     day: ['%A, %b %e, %Y', '%A, %b %e', '-%A, %b %e, %Y'],
 *     week: ['Week from %A, %b %e, %Y', '%A, %b %e', '-%A, %b %e, %Y'],
 *     month: ['%B %Y', '%B', '-%B %Y'],
 *     year: ['%Y', '%Y', '-%Y']
 * }</pre>
 *
 * For each of these array definitions, the first item is the format
 * used when the active time span is one unit. For instance, if the
 * current data applies to one week, the first item of the week array
 * is used. The second and third items are used when the active time
 * span is more than two units. For instance, if the current data applies
 * to two weeks, the second and third item of the week array are used,
 *  and applied to the start and end date of the time span.
 *
 * @type {Object}
 * @product highstock
 * @apioption plotOptions.series.dataGrouping.dateTimeLabelFormats
 */

/**
 * Enable or disable data grouping.
 *
 * @type {Boolean}
 * @default true
 * @product highstock
 * @apioption plotOptions.series.dataGrouping.enabled
 */

/**
 * When data grouping is forced, it runs no matter how small the intervals
 * are. This can be handy for example when the sum should be calculated
 * for values appearing at random times within each hour.
 *
 * @type {Boolean}
 * @default false
 * @product highstock
 * @apioption plotOptions.series.dataGrouping.forced
 */

/**
 * The approximate pixel width of each group. If for example a series
 * with 30 points is displayed over a 600 pixel wide plot area, no grouping
 * is performed. If however the series contains so many points that
 * the spacing is less than the groupPixelWidth, Highcharts will try
 * to group it into appropriate groups so that each is more or less
 * two pixels wide. If multiple series with different group pixel widths
 * are drawn on the same x axis, all series will take the greatest width.
 * For example, line series have 2px default group width, while column
 * series have 10px. If combined, both the line and the column will
 * have 10px by default.
 *
 * @type {Number}
 * @default 2
 * @product highstock
 * @apioption plotOptions.series.dataGrouping.groupPixelWidth
 */

 /**
 * By default only points within the visible range are grouped. Enabling this
 * option will force data grouping to calculate all grouped points for a given
 * dataset. That option prevents for example a column series from calculating
 * a grouped point partially. The effect is similar to
 * [Series.getExtremesFromAll](#plotOptions.series.getExtremesFromAll) but does
 * not affect yAxis extremes.
 *
 * @type {Boolean}
 * @sample {highstock} stock/plotoptions/series-datagrouping-groupall/
 *         Two series with the same data but different groupAll setting
 * @default false
 * @since 6.1.0
 * @product highstock
 * @apioption plotOptions.series.dataGrouping.groupAll
 */

/**
 * Normally, a group is indexed by the start of that group, so for example
 * when 30 daily values are grouped into one month, that month's x value
 * will be the 1st of the month. This apparently shifts the data to
 * the left. When the smoothed option is true, this is compensated for.
 * The data is shifted to the middle of the group, and min and max
 * values are preserved. Internally, this is used in the Navigator series.
 *
 * @type {Boolean}
 * @default false
 * @product highstock
 * @apioption plotOptions.series.dataGrouping.smoothed
 */

/**
 * An array determining what time intervals the data is allowed to be
 * grouped to. Each array item is an array where the first value is
 * the time unit and the second value another array of allowed multiples.
 * Defaults to:
 *
 * <pre>units: [[
 *     'millisecond', // unit name
 *     [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples
 * ], [
 *     'second',
 *     [1, 2, 5, 10, 15, 30]
 * ], [
 *     'minute',
 *     [1, 2, 5, 10, 15, 30]
 * ], [
 *     'hour',
 *     [1, 2, 3, 4, 6, 8, 12]
 * ], [
 *     'day',
 *     [1]
 * ], [
 *     'week',
 *     [1]
 * ], [
 *     'month',
 *     [1, 3, 6]
 * ], [
 *     'year',
 *     null
 * ]]</pre>
 *
 * @type {Array}
 * @product highstock
 * @apioption plotOptions.series.dataGrouping.units
 */

/**
 * The approximate pixel width of each group. If for example a series
 * with 30 points is displayed over a 600 pixel wide plot area, no grouping
 * is performed. If however the series contains so many points that
 * the spacing is less than the groupPixelWidth, Highcharts will try
 * to group it into appropriate groups so that each is more or less
 * two pixels wide. Defaults to `10`.
 *
 * @type {Number}
 * @sample {highstock} stock/plotoptions/series-datagrouping-grouppixelwidth/
 *         Two series with the same data density but different groupPixelWidth
 * @default 10
 * @product highstock
 * @apioption plotOptions.column.dataGrouping.groupPixelWidth
 */

var seriesProto = Series.prototype,
    baseProcessData = seriesProto.processData,
    baseGeneratePoints = seriesProto.generatePoints,

    /**
     *
     */
    commonOptions = {
        approximation: 'average', // average, open, high, low, close, sum
        // enabled: null, // (true for stock charts, false for basic),
        // forced: undefined,
        groupPixelWidth: 2,
        // the first one is the point or start value, the second is the start
        // value if we're dealing with range, the third one is the end value if
        // dealing with a range
        dateTimeLabelFormats: {
            millisecond: [
                '%A, %b %e, %H:%M:%S.%L',
                '%A, %b %e, %H:%M:%S.%L',
                '-%H:%M:%S.%L'
            ],
            second: [
                '%A, %b %e, %H:%M:%S',
                '%A, %b %e, %H:%M:%S',
                '-%H:%M:%S'
            ],
            minute: [
                '%A, %b %e, %H:%M',
                '%A, %b %e, %H:%M',
                '-%H:%M'
            ],
            hour: [
                '%A, %b %e, %H:%M',
                '%A, %b %e, %H:%M',
                '-%H:%M'
            ],
            day: [
                '%A, %b %e, %Y',
                '%A, %b %e',
                '-%A, %b %e, %Y'
            ],
            week: [
                'Week from %A, %b %e, %Y',
                '%A, %b %e',
                '-%A, %b %e, %Y'
            ],
            month: [
                '%B %Y',
                '%B',
                '-%B %Y'
            ],
            year: [
                '%Y',
                '%Y',
                '-%Y'
            ]
        }
        // smoothed = false, // enable this for navigator series only
    },

    specificOptions = { // extends common options
        line: {},
        spline: {},
        area: {},
        areaspline: {},
        column: {
            approximation: 'sum',
            groupPixelWidth: 10
        },
        arearange: {
            approximation: 'range'
        },
        areasplinerange: {
            approximation: 'range'
        },
        columnrange: {
            approximation: 'range',
            groupPixelWidth: 10
        },
        candlestick: {
            approximation: 'ohlc',
            groupPixelWidth: 10
        },
        ohlc: {
            approximation: 'ohlc',
            groupPixelWidth: 5
        }
    },

    // units are defined in a separate array to allow complete overriding in
    // case of a user option
    defaultDataGroupingUnits = H.defaultDataGroupingUnits = [
        [
            'millisecond', // unit name
            [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples
        ], [
            'second',
            [1, 2, 5, 10, 15, 30]
        ], [
            'minute',
            [1, 2, 5, 10, 15, 30]
        ], [
            'hour',
            [1, 2, 3, 4, 6, 8, 12]
        ], [
            'day',
            [1]
        ], [
            'week',
            [1]
        ], [
            'month',
            [1, 3, 6]
        ], [
            'year',
            null
        ]
    ],


    /**
     * Define the available approximation types. The data grouping
     * approximations takes an array or numbers as the first parameter. In case
     * of ohlc, four arrays are sent in as four parameters. Each array consists
     * only of numbers. In case null values belong to the group, the property
     * .hasNulls will be set to true on the array.
     */
    approximations = H.approximations = {
        sum: function (arr) {
            var len = arr.length,
                ret;

            // 1. it consists of nulls exclusively
            if (!len && arr.hasNulls) {
                ret = null;
            // 2. it has a length and real values
            } else if (len) {
                ret = 0;
                while (len--) {
                    ret += arr[len];
                }
            }
            // 3. it has zero length, so just return undefined
            // => doNothing()

            return ret;
        },
        average: function (arr) {
            var len = arr.length,
                ret = approximations.sum(arr);

            // If we have a number, return it divided by the length. If not,
            // return null or undefined based on what the sum method finds.
            if (isNumber(ret) && len) {
                ret = ret / len;
            }

            return ret;
        },
        // The same as average, but for series with multiple values, like area
        // ranges.
        averages: function () { // #5479
            var ret = [];

            each(arguments, function (arr) {
                ret.push(approximations.average(arr));
            });

            // Return undefined when first elem. is undefined and let
            // sum method handle null (#7377)
            return ret[0] === undefined ? undefined : ret;
        },
        open: function (arr) {
            return arr.length ? arr[0] : (arr.hasNulls ? null : undefined);
        },
        high: function (arr) {
            return arr.length ?
                arrayMax(arr) :
                (arr.hasNulls ? null : undefined);
        },
        low: function (arr) {
            return arr.length ?
                arrayMin(arr) :
                (arr.hasNulls ? null : undefined);
        },
        close: function (arr) {
            return arr.length ?
                arr[arr.length - 1] :
                (arr.hasNulls ? null : undefined);
        },
        // ohlc and range are special cases where a multidimensional array is
        // input and an array is output
        ohlc: function (open, high, low, close) {
            open = approximations.open(open);
            high = approximations.high(high);
            low = approximations.low(low);
            close = approximations.close(close);

            if (
                isNumber(open) ||
                isNumber(high) ||
                isNumber(low) ||
                isNumber(close)
            ) {
                return [open, high, low, close];
            }
            // else, return is undefined
        },
        range: function (low, high) {
            low = approximations.low(low);
            high = approximations.high(high);

            if (isNumber(low) || isNumber(high)) {
                return [low, high];
            } else if (low === null && high === null) {
                return null;
            }
            // else, return is undefined
        }
    };

/**
 * Takes parallel arrays of x and y data and groups the data into intervals
 * defined by groupPositions, a collection of starting x values for each group.
 */
seriesProto.groupData = function (xData, yData, groupPositions, approximation) {
    var series = this,
        data = series.data,
        dataOptions = series.options.data,
        groupedXData = [],
        groupedYData = [],
        groupMap = [],
        dataLength = xData.length,
        pointX,
        pointY,
        groupedY,
        // when grouping the fake extended axis for panning,
        // we don't need to consider y
        handleYData = !!yData,
        values = [],
        approximationFn = typeof approximation === 'function' ?
            approximation :
            approximations[approximation] ||
                // if the approximation is not found use default series type
                // approximation (#2914)
                (
                    specificOptions[series.type] &&
                    approximations[specificOptions[series.type].approximation]
                ) || approximations[commonOptions.approximation],
        pointArrayMap = series.pointArrayMap,
        pointArrayMapLength = pointArrayMap && pointArrayMap.length,
        extendedPointArrayMap = ['x'].concat(pointArrayMap || ['y']),
        pos = 0,
        start = 0,
        valuesLen,
        i, j;

    // Calculate values array size from pointArrayMap length
    if (pointArrayMapLength) {
        each(pointArrayMap, function () {
            values.push([]);
        });
    } else {
        values.push([]);
    }
    valuesLen = pointArrayMapLength || 1;

    // Start with the first point within the X axis range (#2696)
    for (i = 0; i <= dataLength; i++) {
        if (xData[i] >= groupPositions[0]) {
            break;
        }
    }

    for (i; i <= dataLength; i++) {

        // when a new group is entered, summarize and initiate
        // the previous group
        while ((
                    groupPositions[pos + 1] !== undefined &&
                    xData[i] >= groupPositions[pos + 1]
                ) || i === dataLength) { // get the last group

            // get group x and y
            pointX = groupPositions[pos];
            series.dataGroupInfo = { start: start, length: values[0].length };
            groupedY = approximationFn.apply(series, values);

            // By default, let options of the first grouped point be passed over
            // to the grouped point. This allows preserving properties like
            // `name` and `color` or custom properties. Implementers can
            // override this from the approximation function, where they can
            // write custom options to `this.dataGroupInfo.options`.
            if (!defined(series.dataGroupInfo.options)) {
                // Convert numbers and arrays into objects
                series.dataGroupInfo.options = merge(
                    series.pointClass.prototype
                        .optionsToObject.call(
                            { series: series },
                            series.options.data[start]
                        )
                );

                // Make sure the raw data (x, y, open, high etc) is not copied
                // over and overwriting approximated data.
                each(extendedPointArrayMap, function (key) {
                    delete series.dataGroupInfo.options[key];
                });
            }

            // push the grouped data
            if (groupedY !== undefined) {
                groupedXData.push(pointX);
                groupedYData.push(groupedY);
                groupMap.push(series.dataGroupInfo);
            }

            // reset the aggregate arrays
            start = i;
            for (j = 0; j < valuesLen; j++) {
                values[j].length = 0; // faster than values[j] = []
                values[j].hasNulls = false;
            }

            // Advance on the group positions
            pos += 1;

            // don't loop beyond the last group
            if (i === dataLength) {
                break;
            }
        }

        // break out
        if (i === dataLength) {
            break;
        }

        // for each raw data point, push it to an array that contains all values
        // for this specific group
        if (pointArrayMap) {

            var index = series.cropStart + i,
                point = (data && data[index]) ||
                    series.pointClass.prototype.applyOptions.apply({
                        series: series
                    }, [dataOptions[index]]),
                val;

            for (j = 0; j < pointArrayMapLength; j++) {
                val = point[pointArrayMap[j]];
                if (isNumber(val)) {
                    values[j].push(val);
                } else if (val === null) {
                    values[j].hasNulls = true;
                }
            }

        } else {
            pointY = handleYData ? yData[i] : null;

            if (isNumber(pointY)) {
                values[0].push(pointY);
            } else if (pointY === null) {
                values[0].hasNulls = true;
            }
        }
    }

    return [groupedXData, groupedYData, groupMap];
};

/**
 * Extend the basic processData method, that crops the data to the current zoom
 * range, with data grouping logic.
 */
seriesProto.processData = function () {
    var series = this,
        chart = series.chart,
        options = series.options,
        dataGroupingOptions = options.dataGrouping,
        groupingEnabled = series.allowDG !== false && dataGroupingOptions &&
            pick(dataGroupingOptions.enabled, chart.options.isStock),
        visible = series.visible || !chart.options.chart.ignoreHiddenSeries,
        hasGroupedData,
        skip,
        lastDataGrouping = this.currentDataGrouping,
        currentDataGrouping,
        croppedData;

    // Run base method
    series.forceCrop = groupingEnabled; // #334
    series.groupPixelWidth = null; // #2110
    series.hasProcessed = true; // #2692

    // Skip if processData returns false or if grouping is disabled (in that
    // order)
    skip = (
        baseProcessData.apply(series, arguments) === false ||
        !groupingEnabled
    );
    if (!skip) {
        series.destroyGroupedData();

        var i,
            processedXData = dataGroupingOptions.groupAll ? series.xData :
                series.processedXData,
            processedYData = dataGroupingOptions.groupAll ? series.yData :
                series.processedYData,
            plotSizeX = chart.plotSizeX,
            xAxis = series.xAxis,
            ordinal = xAxis.options.ordinal,
            groupPixelWidth = series.groupPixelWidth =
                xAxis.getGroupPixelWidth && xAxis.getGroupPixelWidth();

        // Execute grouping if the amount of points is greater than the limit
        // defined in groupPixelWidth
        if (groupPixelWidth) {
            hasGroupedData = true;

            // Force recreation of point instances in series.translate, #5699
            series.isDirty = true;
            series.points = null; // #6709

            var extremes = xAxis.getExtremes(),
                xMin = extremes.min,
                xMax = extremes.max,
                groupIntervalFactor = (
                    ordinal &&
                    xAxis.getGroupIntervalFactor(xMin, xMax, series)
                ) || 1,
                interval =
                    (groupPixelWidth * (xMax - xMin) / plotSizeX) *
                    groupIntervalFactor,
                groupPositions = xAxis.getTimeTicks(
                    xAxis.normalizeTimeTickInterval(
                        interval,
                        dataGroupingOptions.units || defaultDataGroupingUnits
                    ),
                    // Processed data may extend beyond axis (#4907)
                    Math.min(xMin, processedXData[0]),
                    Math.max(xMax, processedXData[processedXData.length - 1]),
                    xAxis.options.startOfWeek,
                    processedXData,
                    series.closestPointRange
                ),
                groupedData = seriesProto.groupData.apply(
                    series,
                    [
                        processedXData,
                        processedYData,
                        groupPositions,
                        dataGroupingOptions.approximation
                    ]),
                groupedXData = groupedData[0],
                groupedYData = groupedData[1];

            // Prevent the smoothed data to spill out left and right, and make
            // sure data is not shifted to the left
            if (dataGroupingOptions.smoothed && groupedXData.length) {
                i = groupedXData.length - 1;
                groupedXData[i] = Math.min(groupedXData[i], xMax);
                while (i-- && i > 0) {
                    groupedXData[i] += interval / 2;
                }
                groupedXData[0] = Math.max(groupedXData[0], xMin);
            }

            // Record what data grouping values were used
            currentDataGrouping = groupPositions.info;
            series.closestPointRange = groupPositions.info.totalRange;
            series.groupMap = groupedData[2];

            // Make sure the X axis extends to show the first group (#2533)
            // But only for visible series (#5493, #6393)
            if (
                defined(groupedXData[0]) &&
                groupedXData[0] < xAxis.dataMin &&
                visible
            ) {
                if (
                    (
                        !defined(xAxis.options.min) &&
                        xAxis.min <= xAxis.dataMin
                    ) ||
                    xAxis.min === xAxis.dataMin
                ) {
                    xAxis.min = groupedXData[0];
                }
                xAxis.dataMin = groupedXData[0];
            }

            // We calculated all group positions but we should render
            // only the ones within the visible range
            if (dataGroupingOptions.groupAll) {
                croppedData = series.cropData(
                    groupedXData,
                    groupedYData,
                    xAxis.min,
                    xAxis.max,
                    1 // Ordinal xAxis will remove left-most points otherwise
                );
                groupedXData = croppedData.xData;
                groupedYData = croppedData.yData;
            }
            // Set series props
            series.processedXData = groupedXData;
            series.processedYData = groupedYData;
        } else {
            series.groupMap = null;
        }
        series.hasGroupedData = hasGroupedData;
        series.currentDataGrouping = currentDataGrouping;

        series.preventGraphAnimation =
            (lastDataGrouping && lastDataGrouping.totalRange) !==
            (currentDataGrouping && currentDataGrouping.totalRange);
    }
};

/**
 * Destroy the grouped data points. #622, #740
 */
seriesProto.destroyGroupedData = function () {

    var groupedData = this.groupedData;

    // clear previous groups
    each(groupedData || [], function (point, i) {
        if (point) {
            groupedData[i] = point.destroy ? point.destroy() : null;
        }
    });
    this.groupedData = null;
};

/**
 * Override the generatePoints method by adding a reference to grouped data
 */
seriesProto.generatePoints = function () {

    baseGeneratePoints.apply(this);

    // Record grouped data in order to let it be destroyed the next time
    // processData runs
    this.destroyGroupedData(); // #622
    this.groupedData = this.hasGroupedData ? this.points : null;
};

/**
 * Override point prototype to throw a warning when trying to update grouped
 * points
 */
addEvent(Point, 'update', function () {
    if (this.dataGroup) {
        H.error(24);
        return false;
    }
});

/**
 * Extend the original method, make the tooltip's header reflect the grouped
 * range
 */
wrap(Tooltip.prototype, 'tooltipFooterHeaderFormatter', function (
    proceed,
    labelConfig,
    isFooter
) {
    var tooltip = this,
        time = this.chart.time,
        series = labelConfig.series,
        options = series.options,
        tooltipOptions = series.tooltipOptions,
        dataGroupingOptions = options.dataGrouping,
        xDateFormat = tooltipOptions.xDateFormat,
        xDateFormatEnd,
        xAxis = series.xAxis,
        currentDataGrouping,
        dateTimeLabelFormats,
        labelFormats,
        formattedKey;

    // apply only to grouped series
    if (
        xAxis &&
        xAxis.options.type === 'datetime' &&
        dataGroupingOptions &&
        isNumber(labelConfig.key)
    ) {

        // set variables
        currentDataGrouping = series.currentDataGrouping;
        dateTimeLabelFormats = dataGroupingOptions.dateTimeLabelFormats;

        // if we have grouped data, use the grouping information to get the
        // right format
        if (currentDataGrouping) {
            labelFormats = dateTimeLabelFormats[currentDataGrouping.unitName];
            if (currentDataGrouping.count === 1) {
                xDateFormat = labelFormats[0];
            } else {
                xDateFormat = labelFormats[1];
                xDateFormatEnd = labelFormats[2];
            }
        // if not grouped, and we don't have set the xDateFormat option, get the
        // best fit, so if the least distance between points is one minute, show
        // it, but if the least distance is one day, skip hours and minutes etc.
        } else if (!xDateFormat && dateTimeLabelFormats) {
            xDateFormat = tooltip.getXDateFormat(
                labelConfig,
                tooltipOptions,
                xAxis
            );
        }

        // now format the key
        formattedKey = time.dateFormat(xDateFormat, labelConfig.key);
        if (xDateFormatEnd) {
            formattedKey += time.dateFormat(
                xDateFormatEnd,
                labelConfig.key + currentDataGrouping.totalRange - 1
            );
        }

        // return the replaced format
        return format(
            tooltipOptions[(isFooter ? 'footer' : 'header') + 'Format'], {
                point: extend(labelConfig.point, { key: formattedKey }),
                series: series
            },
            time
        );

    }

    // else, fall back to the regular formatter
    return proceed.call(tooltip, labelConfig, isFooter);
});

/**
 * Destroy grouped data on series destroy
 */
addEvent(Series, 'destroy', seriesProto.destroyGroupedData);


// Handle default options for data grouping. This must be set at runtime because
// some series types are defined after this.
addEvent(Series, 'afterSetOptions', function (e) {

    var options = e.options,
        type = this.type,
        plotOptions = this.chart.options.plotOptions,
        defaultOptions = defaultPlotOptions[type].dataGrouping,
        // External series, for example technical indicators should also
        // inherit commonOptions which are not available outside this module
        baseOptions = this.useCommonDataGrouping && commonOptions;

    if (specificOptions[type] || baseOptions) { // #1284
        if (!defaultOptions) {
            defaultOptions = merge(commonOptions, specificOptions[type]);
        }

        options.dataGrouping = merge(
            baseOptions,
            defaultOptions,
            plotOptions.series && plotOptions.series.dataGrouping, // #1228
            plotOptions[type].dataGrouping, // Set by the StockChart constructor
            this.userOptions.dataGrouping
        );
    }

    if (this.chart.options.isStock) {
        this.requireSorting = true;
    }
});


/**
 * When resetting the scale reset the hasProccessed flag to avoid taking
 * previous data grouping of neighbour series into accound when determining
 * group pixel width (#2692).
 */
addEvent(Axis, 'afterSetScale', function () {
    each(this.series, function (series) {
        series.hasProcessed = false;
    });
});

/**
 * Get the data grouping pixel width based on the greatest defined individual
 * width
 * of the axis' series, and if whether one of the axes need grouping.
 */
Axis.prototype.getGroupPixelWidth = function () {

    var series = this.series,
        len = series.length,
        i,
        groupPixelWidth = 0,
        doGrouping = false,
        dataLength,
        dgOptions;

    // If multiple series are compared on the same x axis, give them the same
    // group pixel width (#334)
    i = len;
    while (i--) {
        dgOptions = series[i].options.dataGrouping;
        if (dgOptions) {
            groupPixelWidth = Math.max(
                groupPixelWidth,
                dgOptions.groupPixelWidth
            );

        }
    }

    // If one of the series needs grouping, apply it to all (#1634)
    i = len;
    while (i--) {
        dgOptions = series[i].options.dataGrouping;

        if (dgOptions && series[i].hasProcessed) { // #2692

            dataLength = (series[i].processedXData || series[i].data).length;

            // Execute grouping if the amount of points is greater than the
            // limit defined in groupPixelWidth
            if (
                series[i].groupPixelWidth ||
                dataLength > (this.chart.plotSizeX / groupPixelWidth) ||
                (dataLength && dgOptions.forced)
            ) {
                doGrouping = true;
            }
        }
    }

    return doGrouping ? groupPixelWidth : 0;
};

/**
 * Highstock only. Force data grouping on all the axis' series.
 *
 * @param  {SeriesDatagroupingOptions} [dataGrouping]
 *         A `dataGrouping` configuration. Use `false` to disable data grouping
 *         dynamically.
 * @param  {Boolean} [redraw=true]
 *         Whether to redraw the chart or wait for a later call to {@link
 *         Chart#redraw}.
 *
 * @function setDataGrouping
 * @memberof Axis.prototype
 */
Axis.prototype.setDataGrouping = function (dataGrouping, redraw) {
    var i;

    redraw = pick(redraw, true);

    if (!dataGrouping) {
        dataGrouping = {
            forced: false,
            units: null
        };
    }

    // Axis is instantiated, update all series
    if (this instanceof Axis) {
        i = this.series.length;
        while (i--) {
            this.series[i].update({
                dataGrouping: dataGrouping
            }, false);
        }

    // Axis not yet instanciated, alter series options
    } else {
        each(this.chart.options.series, function (seriesOptions) {
            seriesOptions.dataGrouping = dataGrouping;
        }, false);
    }

    // Clear ordinal slope, so we won't accidentaly use the old one (#7827)
    this.ordinalSlope = null;

    if (redraw) {
        this.chart.redraw();
    }
};



/* ****************************************************************************
 * End data grouping module                                                   *
 ******************************************************************************/