"use strict";
/* file: hyperloglog.ts
MIT License

Copyright (c) 2019-2020 Thomas Minier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the 'Software'), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var base_filter_1 = __importDefault(require("../base-filter"));
var exportable_1 = require("../exportable");
var utils_1 = require("../utils");
// 2^32, computed as a constant as we use it a lot in the HyperLogLog algorithm
var TWO_POW_32 = Math.pow(2, 32);
/**
 * Estimlate the bias-correction constant, denoted alpha in the algorithm, based on the number of registers.
 * As alpha is pretty expensive to compute, we estimate it with the formula from Flajolet et al.
 * @param m - Number of registers in the HyperLogLog algorithm
 * @return The estimated bias-correction constant
 */
function computeAlpha(m) {
    switch (m) {
        case 16:
            return 0.673;
        case 32:
            return 0.697;
        case 64:
            return 0.709;
        default:
            return 0.7213 / (1.0 + 1.079 / m);
    }
}
/**
 * HyperLogLog is an algorithm for the count-distinct problem, approximating the number of distinct elements in a multiset.
 * @see HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm {@link http://algo.inria.fr/flajolet/Publications/FlFuGaMe07.pdf}
 * @author Thomas Minier
 */
var HyperLogLog = /** @class */ (function (_super) {
    __extends(HyperLogLog, _super);
    /**
     * Constructor
     * @param nbRegisters - The number of registers to use
     */
    function HyperLogLog(nbRegisters) {
        var _this = _super.call(this) || this;
        _this._nbRegisters = nbRegisters;
        _this._nbBytesPerHash = Math.round(Math.log2(nbRegisters));
        _this._correctionBias = computeAlpha(nbRegisters);
        _this._registers = utils_1.allocateArray(_this._nbRegisters, 0);
        return _this;
    }
    HyperLogLog_1 = HyperLogLog;
    Object.defineProperty(HyperLogLog.prototype, "nbRegisters", {
        /**
         * Get the number of registers used by the HyperLogLog
         */
        get: function () {
            return this._nbRegisters;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Update The multiset with a new element
     * @param element - Element to add
     */
    HyperLogLog.prototype.update = function (element) {
        // const hashedValue = Buffer.from(hashAsString(element, this.seed))
        var hashedValue = utils_1.hashAsInt(element, this.seed).toString(2);
        var registerIndex = 1 + parseInt(hashedValue.slice(0, this._nbBytesPerHash - 1), 2);
        // find the left most 1-bit in the second part of the buffer    
        var secondPart = hashedValue.slice(this._nbBytesPerHash);
        var posLeftMost = 0;
        while (secondPart[posLeftMost] !== '1' && posLeftMost < secondPart.length - 1) {
            posLeftMost++;
        }
        // update the register
        this._registers[registerIndex] = Math.max(this._registers[registerIndex], posLeftMost);
    };
    /**
     * Estimate the cardinality of the multiset
     * @return The estimated cardinality of the multiset
     */
    HyperLogLog.prototype.count = function (round) {
        if (round === void 0) { round = false; }
        // Use the standard HyperLogLog estimator
        var harmonicMean = this._registers.reduce(function (acc, value) { return acc + Math.pow(2, -value); }, 0);
        var estimation = (this._correctionBias * Math.pow(this._nbRegisters, 2)) / harmonicMean;
        // use linear counting to correct the estimation if E < 5m/2 and some registers are set to zero
        /*if (estimation < ((5/2) * this._nbRegisters) && this._registers.some(value => value === 0)) {
          const nbZeroRegisters = this._registers.filter(value => value === 0).length
          estimation = this._nbRegisters * Math.log(this._nbRegisters / nbZeroRegisters)
        }*/
        // correct the estimation for very large registers
        if (estimation > (TWO_POW_32 / 30)) {
            estimation = -TWO_POW_32 * Math.log(1 - (estimation / TWO_POW_32));
        }
        // round if required
        if (round) {
            estimation = Math.round(estimation);
        }
        return estimation;
    };
    /**
     * Compute the accuracy of the cardinality estimation produced by this HyperLogLog
     * @return The accuracy of the cardinality estimation
     */
    HyperLogLog.prototype.accuracy = function () {
        return 1.04 / Math.sqrt(this._nbRegisters);
    };
    /**
     * Perform the union with another HyperLogLog multiset
     * @param other - Multiset ot merge with
     * @return The union of the two multisets
     */
    HyperLogLog.prototype.merge = function (other) {
        if (this.nbRegisters !== other.nbRegisters) {
            throw new Error("Two HyperLogLog must have the same number of registers to be merged. Tried to merge two HyperLogLog with m = " + this.nbRegisters + " and m = " + other.nbRegisters);
        }
        var newSketch = new HyperLogLog_1(this.nbRegisters);
        for (var i = 0; i < this.nbRegisters - 1; i++) {
            newSketch._registers[i] = Math.max(this._registers[i], other._registers[i]);
        }
        return newSketch;
    };
    /**
     * Check if another HyperLogLog is equal to this one
     * @param  other - The HyperLogLog to compare to this one
     * @return True if they are equal, false otherwise
     */
    HyperLogLog.prototype.equals = function (other) {
        if (this.nbRegisters !== other.nbRegisters) {
            return false;
        }
        for (var i = 0; i < this.nbRegisters - 1; i++) {
            if (this._registers[i] !== other._registers[i]) {
                return false;
            }
        }
        return true;
    };
    var HyperLogLog_1;
    __decorate([
        exportable_1.Field(),
        __metadata("design:type", Number)
    ], HyperLogLog.prototype, "_nbRegisters", void 0);
    __decorate([
        exportable_1.Field(),
        __metadata("design:type", Number)
    ], HyperLogLog.prototype, "_nbBytesPerHash", void 0);
    __decorate([
        exportable_1.Field(),
        __metadata("design:type", Number)
    ], HyperLogLog.prototype, "_correctionBias", void 0);
    __decorate([
        exportable_1.Field(),
        __metadata("design:type", Array)
    ], HyperLogLog.prototype, "_registers", void 0);
    HyperLogLog = HyperLogLog_1 = __decorate([
        exportable_1.AutoExportable('HyperLogLog', ['_seed']),
        __param(0, exportable_1.Parameter('_nbRegisters')),
        __metadata("design:paramtypes", [Number])
    ], HyperLogLog);
    return HyperLogLog;
}(base_filter_1.default));
exports.default = HyperLogLog;
